// ui.jsx — shared atoms: Logo, Avatar, Stars, Chip, primary button etc.

const COLORS = {
  bg: '#0B0B0B',
  bg2: '#141414',
  card: '#1A1A1A',
  card2: '#222222',
  border: 'rgba(212,175,55,0.14)',
  borderSoft: 'rgba(255,255,255,0.06)',
  text: '#FFFFFF',
  text2: 'rgba(255,255,255,0.65)',
  text3: 'rgba(255,255,255,0.4)',
  gold: '#D4AF37',
  goldDark: '#B6932B',
  goldSoft: 'rgba(212,175,55,0.14)',
  green: '#34D399',
  red: '#F87171',
};

// Logo: T inside shield, gold gradient
function TrustaLogo({ size = 64, mark = true }) {
  const id = React.useId();
  return (
    <svg width={size} height={size * (74 / 64)} viewBox="0 0 64 74" style={{ display: 'block' }}>
      <defs>
        <linearGradient id={`g-${id}`} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0" stopColor="#EFD076" />
          <stop offset="0.5" stopColor="#D4AF37" />
          <stop offset="1" stopColor="#9A7A1F" />
        </linearGradient>
      </defs>
      {/* shield outline */}
      <path
        d="M32 2 L60 10 L60 38 C60 54 48 66 32 72 C16 66 4 54 4 38 L4 10 Z"
        fill="none"
        stroke={`url(#g-${id})`}
        strokeWidth="2.5"
      />
      {/* T mark */}
      {mark && (
        <g fill={`url(#g-${id})`}>
          <rect x="14" y="20" width="36" height="6" rx="1" />
          <rect x="29" y="20" width="6" height="32" rx="1" />
          {/* serif feet */}
          <rect x="13" y="20" width="3" height="10" rx="1" />
          <rect x="48" y="20" width="3" height="10" rx="1" />
        </g>
      )}
    </svg>
  );
}

function Wordmark({ size = 28, color = '#D4AF37', tracking = 0.32 }) {
  return (
    <span style={{
      fontFamily: '"Playfair Display", Georgia, serif',
      fontWeight: 700,
      fontSize: size,
      color,
      letterSpacing: tracking + 'em',
      lineHeight: 1,
    }}>TRUSTA</span>
  );
}

function Avatar({ src, size = 40, ring = false, verified = false }) {
  return (
    <div style={{ position: 'relative', width: size, height: size, flexShrink: 0 }}>
      <div style={{
        width: size, height: size, borderRadius: '50%',
        background: `url(${src}) center/cover`,
        border: ring ? `2px solid ${COLORS.gold}` : 'none',
        boxShadow: ring ? '0 0 0 2px rgba(0,0,0,0.6)' : 'none',
      }} />
      {verified && (
        <div style={{
          position: 'absolute', bottom: -2, right: -2,
          width: size * 0.35, height: size * 0.35, minWidth: 14, minHeight: 14,
          borderRadius: '50%', background: COLORS.gold,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          border: `2px solid ${COLORS.bg}`,
        }}>
          <svg width="8" height="8" viewBox="0 0 8 8">
            <path d="M1.5 4 L3.2 5.5 L6.5 2" stroke="#000" strokeWidth="1.4" fill="none" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
        </div>
      )}
    </div>
  );
}

function Stars({ value = 5, size = 12, count = true }) {
  return (
    <div style={{ display: 'inline-flex', gap: 1, alignItems: 'center' }}>
      {[1, 2, 3, 4, 5].map(i => (
        <svg key={i} width={size} height={size} viewBox="0 0 12 12">
          <path
            d="M6 1 L7.5 4.4 L11 4.9 L8.5 7.3 L9.1 11 L6 9.2 L2.9 11 L3.5 7.3 L1 4.9 L4.5 4.4 Z"
            fill={i <= Math.round(value) ? COLORS.gold : 'rgba(255,255,255,0.18)'}
          />
        </svg>
      ))}
    </div>
  );
}

function GoldButton({ children, onClick, disabled, full = true, style = {} }) {
  return (
    <button
      onClick={onClick}
      disabled={disabled}
      style={{
        width: full ? '100%' : 'auto',
        height: 52,
        borderRadius: 14,
        border: 'none',
        background: disabled
          ? 'rgba(212,175,55,0.3)'
          : 'linear-gradient(180deg, #E4C25C 0%, #D4AF37 50%, #B6932B 100%)',
        color: '#0A0A0A',
        fontFamily: 'Inter, system-ui, sans-serif',
        fontSize: 16,
        fontWeight: 700,
        letterSpacing: '0.02em',
        cursor: disabled ? 'default' : 'pointer',
        boxShadow: disabled ? 'none' : '0 8px 24px -8px rgba(212,175,55,0.5), inset 0 1px 0 rgba(255,255,255,0.4)',
        transition: 'transform 0.1s',
        ...style,
      }}
      onMouseDown={e => !disabled && (e.currentTarget.style.transform = 'scale(0.98)')}
      onMouseUp={e => !disabled && (e.currentTarget.style.transform = 'scale(1)')}
      onMouseLeave={e => !disabled && (e.currentTarget.style.transform = 'scale(1)')}
    >
      {children}
    </button>
  );
}

function GhostButton({ children, onClick, full = true, style = {} }) {
  return (
    <button
      onClick={onClick}
      style={{
        width: full ? '100%' : 'auto',
        height: 52,
        borderRadius: 14,
        border: `1px solid ${COLORS.gold}`,
        background: 'transparent',
        color: COLORS.gold,
        fontFamily: 'Inter, system-ui, sans-serif',
        fontSize: 16,
        fontWeight: 600,
        cursor: 'pointer',
        ...style,
      }}
    >
      {children}
    </button>
  );
}

// Bottom tab bar (5 tabs, center is FAB-style "+")
function TabBar({ active, onChange, t }) {
  // Badge unread sur l'onglet Alerts
  const [unread, setUnread] = React.useState(() =>
    (window.TrustaNotifStore && window.TrustaNotifStore.getUnread()) || 0
  );
  React.useEffect(() => {
    if (!window.TrustaNotifStore) return;
    setUnread(window.TrustaNotifStore.getUnread());
    return window.TrustaNotifStore.subscribe(setUnread);
  }, []);

  const Icon = ({ name, fill }) => {
    const c = fill;
    switch (name) {
      case 'home': return <svg width="22" height="22" viewBox="0 0 22 22"><path d="M3 10 L11 3 L19 10 V19 H13 V13 H9 V19 H3 Z" fill="none" stroke={c} strokeWidth="1.6" strokeLinejoin="round" /></svg>;
      case 'chat': return <svg width="22" height="22" viewBox="0 0 22 22"><path d="M3 5 H19 V15 H12 L7 19 V15 H3 Z" fill="none" stroke={c} strokeWidth="1.6" strokeLinejoin="round" /></svg>;
      case 'alert': return <svg width="22" height="22" viewBox="0 0 22 22"><path d="M5 9 C5 6 8 4 11 4 C14 4 17 6 17 9 V14 L19 16 H3 L5 14 Z" fill="none" stroke={c} strokeWidth="1.6" strokeLinejoin="round" /><path d="M9 18 C9 19.5 10 20 11 20 C12 20 13 19.5 13 18" stroke={c} strokeWidth="1.6" fill="none" /></svg>;
      case 'profile': return <svg width="22" height="22" viewBox="0 0 22 22"><circle cx="11" cy="8" r="4" fill="none" stroke={c} strokeWidth="1.6" /><path d="M3 19 C3 15 7 13 11 13 C15 13 19 15 19 19" fill="none" stroke={c} strokeWidth="1.6" strokeLinecap="round" /></svg>;
    }
  };

  const tabs = [
    { id: 'home', label: t('nav_home') },
    { id: 'chat', label: t('nav_chat') },
    { id: 'post', label: '' }, // FAB
    { id: 'alert', label: t('nav_alerts') },
    { id: 'profile', label: t('nav_profile') },
  ];

  return (
    <div style={{
      position: 'absolute', bottom: 0, left: 0, right: 0, zIndex: 30,
      paddingBottom: 28, paddingTop: 8,
      background: 'linear-gradient(180deg, rgba(11,11,11,0) 0%, rgba(11,11,11,0.95) 30%, #0B0B0B 100%)',
      backdropFilter: 'blur(14px)',
    }}>
      <div style={{
        display: 'flex', alignItems: 'flex-end', justifyContent: 'space-around',
        padding: '0 16px', height: 56,
      }}>
        {tabs.map(tab => {
          if (tab.id === 'post') {
            return (
              <button
                key={tab.id}
                onClick={() => onChange('post')}
                style={{
                  width: 56, height: 56, borderRadius: 18,
                  background: 'linear-gradient(180deg, #E4C25C, #B6932B)',
                  border: 'none', cursor: 'pointer',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  boxShadow: '0 10px 28px -6px rgba(212,175,55,0.55), inset 0 1px 0 rgba(255,255,255,0.4)',
                  marginBottom: 4,
                }}
              >
                <svg width="24" height="24" viewBox="0 0 24 24">
                  <path d="M12 5 V19 M5 12 H19" stroke="#0A0A0A" strokeWidth="2.6" strokeLinecap="round" />
                </svg>
              </button>
            );
          }
          const isActive = active === tab.id;
          const c = isActive ? COLORS.gold : COLORS.text3;
          const showBadge = tab.id === 'alert' && unread > 0;
          return (
            <button
              key={tab.id}
              onClick={() => onChange(tab.id)}
              style={{
                background: 'transparent', border: 'none', cursor: 'pointer',
                display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
                width: 60, position: 'relative',
              }}
            >
              <div style={{ position: 'relative' }}>
                <Icon name={tab.id} fill={c} />
                {showBadge && (
                  <div style={{
                    position: 'absolute', top: -4, right: -8,
                    minWidth: 16, height: 16, borderRadius: 8,
                    background: COLORS.gold, color: '#0A0A0A',
                    fontFamily: 'Inter', fontSize: 10, fontWeight: 700,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    padding: '0 4px',
                  }}>{unread > 99 ? '99+' : unread}</div>
                )}
              </div>
              <span style={{
                fontFamily: 'Inter, system-ui', fontSize: 10, fontWeight: 500,
                color: c, letterSpacing: 0.2,
              }}>{tab.label}</span>
            </button>
          );
        })}
      </div>
    </div>
  );
}

// Top header (custom, replaces IOSNavBar)
function Header({ left, right, title, sub, dark = true, onBack, big = false }) {
  return (
    <div style={{
      paddingTop: 56, paddingBottom: 12, paddingLeft: 20, paddingRight: 20,
      display: 'flex', alignItems: 'center', gap: 12, position: 'relative', zIndex: 5,
    }}>
      {onBack ? (
        <button onClick={onBack} style={{
          width: 38, height: 38, borderRadius: 12,
          background: 'rgba(255,255,255,0.06)', border: '1px solid rgba(255,255,255,0.08)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          cursor: 'pointer', flexShrink: 0,
        }}>
          <svg width="14" height="14" viewBox="0 0 14 14"><path d="M9 2 L3 7 L9 12" stroke="#fff" strokeWidth="1.8" fill="none" strokeLinecap="round" strokeLinejoin="round" /></svg>
        </button>
      ) : left}
      <div style={{ flex: 1, minWidth: 0 }}>
        {sub && <div style={{ fontSize: 12, color: COLORS.text3, fontFamily: 'Inter, system-ui', marginBottom: 2 }}>{sub}</div>}
        <div style={{
          fontFamily: big ? '"Playfair Display", serif' : 'Inter, system-ui',
          fontSize: big ? 26 : 17, fontWeight: big ? 600 : 600, color: '#fff',
          whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
        }}>{title}</div>
      </div>
      {right}
    </div>
  );
}

// === HeartButton — favoris (cœur, état synchronisé via TrustaFavStore) ===
function HeartButton({ kind, id, size = 22, style = {}, onChange }) {
  const numId = Number(id || 0);
  const [fav, setFav] = React.useState(() =>
    !!(window.TrustaFavStore && window.TrustaFavStore.isFav(kind, numId))
  );
  const [busy, setBusy] = React.useState(false);

  React.useEffect(() => {
    if (!window.TrustaFavStore) return;
    const update = () => setFav(window.TrustaFavStore.isFav(kind, numId));
    update();
    return window.TrustaFavStore.subscribe(update);
  }, [kind, numId]);

  const handleClick = async (e) => {
    if (e) { e.stopPropagation(); e.preventDefault(); }
    if (busy || !numId || !window.TrustaFavStore) return;
    setBusy(true);
    try {
      const newVal = await window.TrustaFavStore.toggle(kind, numId);
      if (onChange) onChange(newVal);
    } catch (err) {
      console.error('toggle fav failed', err);
    } finally {
      setBusy(false);
    }
  };

  const fillColor = fav ? COLORS.gold : 'transparent';
  const strokeColor = fav ? COLORS.gold : 'rgba(255,255,255,0.85)';

  return (
    <button onClick={handleClick} aria-label="favori" style={{
      width: size + 14, height: size + 14, borderRadius: (size + 14) / 2,
      background: 'rgba(0,0,0,0.5)', border: '1px solid rgba(255,255,255,0.1)',
      backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)',
      cursor: busy ? 'not-allowed' : 'pointer',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      transition: 'transform 0.12s ease',
      transform: fav ? 'scale(1.05)' : 'scale(1)',
      ...style,
    }}>
      <svg width={size} height={size} viewBox="0 0 24 24"
           fill={fillColor} stroke={strokeColor} strokeWidth="1.8"
           strokeLinecap="round" strokeLinejoin="round">
        <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/>
      </svg>
    </button>
  );
}
window.HeartButton = HeartButton;

window.COLORS = COLORS;
window.TrustaLogo = TrustaLogo;
window.Wordmark = Wordmark;
window.Avatar = Avatar;
window.Stars = Stars;
window.GoldButton = GoldButton;
window.GhostButton = GhostButton;
window.TabBar = TabBar;
window.Header = Header;
