// Shared components for WordyTrainer landing
// Provides: WordyLogo, PopupCard, DesktopWithPopup, Eyebrow, Section, IconSlot

const { useState, useEffect, useRef } = React;

/* ---------- Logo ---------- */
function WordyMark({ size = 36 }) {
  // The W-in-orange-circle mark. Drawn in SVG so it stays crisp on any background.
  return (
    <svg viewBox="0 0 100 100" width={size} height={size} aria-label="WordyTrainer">
      <defs>
        <linearGradient id="wr" x1="0" y1="0" x2="1" y2="1">
          <stop offset="0" stopColor="#FF7A3D" />
          <stop offset="1" stopColor="#FF4A14" />
        </linearGradient>
      </defs>
      <circle cx="50" cy="50" r="46" fill="url(#wr)" />
      <path
        d="M22 34 L35 70 L45 44 L55 70 L68 34"
        stroke="white" strokeWidth="7" fill="none"
        strokeLinecap="round" strokeLinejoin="round"
      />
    </svg>
  );
}

function WordyLogo({ size = 32, color = 'var(--ink)', variant = 'brand' }) {
  // Brand variant uses the official PNG (W mark + "Wordy the app" wordmark).
  // It contains its own colour, so we don't recolour it.
  if (variant === 'brand') {
    // The PNG is 250×61 — a ratio of ~4.1. We size by height so it lines up
    // with adjacent buttons. `size` here means desired height in px.
    return (
      <img
        src="assets/wordy_logo_brand.png"
        alt="Wordy the app"
        style={{ height: size, width: 'auto', display: 'block' }}
      />
    );
  }
  // Mark-only fallback (legacy)
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
      <WordyMark size={size} />
      <span style={{
        fontFamily: 'var(--font-sans)',
        fontWeight: 600,
        fontSize: size * 0.56,
        letterSpacing: '-0.02em',
        color,
      }}>
        WordyTrainer
      </span>
    </div>
  );
}

// Brand logo helper — wraps the PNG with light/dark-aware backdrop tweaks.
// On dark sections the PNG sits fine (it has its own white-glow circle),
// but text portion ("Wordy the app") is dark — we apply a light/dark
// inversion via filter only when explicitly asked.
function WordyBrandLogo({ height = 32, onDark = false }) {
  return (
    <img
      src={onDark ? 'assets/wordy_logo_brand_light.png' : 'assets/wordy_logo_brand.png'}
      alt="Wordy the app"
      style={{
        height,
        width: 'auto',
        display: 'block',
      }}
    />
  );
}

/* ---------- Pop-up card (hero metaphor) ---------- */
function PopupCard({ word = 'seat', transcription = '[siːt]', translation = 'сиденье', meta, onDismiss, compact = false }) {
  return (
    <div className="popup-card" style={compact ? { minWidth: 240, padding: '18px 20px 16px' } : {}}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 }}>
        <div>
          <div className="popup-word">
            <span>{word}</span>
            <span className="popup-transcription">{transcription}</span>
          </div>
          <div className="popup-translation">{translation}</div>
        </div>
        <button
          onClick={onDismiss}
          aria-label="Dismiss"
          style={{
            width: 24, height: 24, borderRadius: 12,
            background: 'rgba(255,255,255,0.08)',
            color: 'rgba(255,255,255,0.5)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 14, lineHeight: 1,
          }}
        >×</button>
      </div>
      {meta && (
        <div className="popup-meta">
          <span style={{ width: 6, height: 6, borderRadius: 3, background: 'var(--accent)', animation: 'pulseDot 1.6s ease-in-out infinite' }}></span>
          {meta}
        </div>
      )}
    </div>
  );
}

/* ---------- Desktop frame with pop-up overlaid (hero visual) ---------- */
function DesktopWithPopup({ screenshot, popup, popupPos = 'br' }) {
  // popupPos: 'br' | 'bl' | 'tr' | 'tl'
  const posMap = {
    br: { right: '6%', bottom: '10%' },
    bl: { left: '6%', bottom: '10%' },
    tr: { right: '6%', top: '14%' },
    tl: { left: '6%', top: '14%' },
  };
  return (
    <div className="macos-window" style={{ position: 'relative' }}>
      <div className="macos-bar">
        <span className="dot r"></span>
        <span className="dot y"></span>
        <span className="dot g"></span>
        <span style={{ flex: 1, textAlign: 'center', fontSize: 12, color: 'rgba(255,255,255,0.4)' }}>WordyTrainer</span>
      </div>
      <div style={{ position: 'relative', aspectRatio: '1920 / 1099', background: '#151419' }}>
        {screenshot && (
          <img src={screenshot} alt="WordyTrainer screen" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
        )}
        {popup && (
          <div style={{ position: 'absolute', ...posMap[popupPos], animation: 'popIn 0.6s cubic-bezier(.2,.9,.3,1) both' }}>
            {popup}
          </div>
        )}
      </div>
    </div>
  );
}

/* ---------- Section chrome ---------- */
function Eyebrow({ children, color }) {
  return <div className="eyebrow" style={color ? { color } : undefined}>{children}</div>;
}

function Section({ children, id, screenLabel, bg, style, pad = true }) {
  return (
    <section
      id={id}
      data-screen-label={screenLabel}
      style={{
        background: bg,
        paddingBlock: pad ? 'var(--section-y)' : 0,
        ...style,
      }}
    >
      <div className="wrap">{children}</div>
    </section>
  );
}

/* ---------- Simple icon slots (line style) ---------- */
function LineIcon({ name, size = 22, color = 'currentColor' }) {
  const stroke = { stroke: color, strokeWidth: 1.6, fill: 'none', strokeLinecap: 'round', strokeLinejoin: 'round' };
  const map = {
    sparkles: <g {...stroke}><path d="M12 4 L13.5 9 L18 10.5 L13.5 12 L12 17 L10.5 12 L6 10.5 L10.5 9 Z"/><path d="M18 4 L18.7 6 L20.5 6.7 L18.7 7.4 L18 9.5"/></g>,
    bell: <g {...stroke}><path d="M6 16 L18 16 L16.5 14 V10 A4.5 4.5 0 0 0 7.5 10 V14 Z"/><path d="M10.5 19 A 1.8 1.8 0 0 0 13.5 19"/></g>,
    upload: <g {...stroke}><path d="M12 4 V14 M8 8 L12 4 L16 8"/><path d="M5 15 V18 A2 2 0 0 0 7 20 H17 A2 2 0 0 0 19 18 V15"/></g>,
    globe: <g {...stroke}><circle cx="12" cy="12" r="8"/><path d="M4 12 H20 M12 4 C16 8 16 16 12 20 C8 16 8 8 12 4"/></g>,
    chat: <g {...stroke}><path d="M5 6 H19 A2 2 0 0 1 21 8 V15 A2 2 0 0 1 19 17 H13 L9 21 V17 H5 A2 2 0 0 1 3 15 V8 A2 2 0 0 1 5 6Z"/></g>,
    wand: <g {...stroke}><path d="M5 19 L15 9 M13 7 L17 11"/><path d="M19 5 L20 6 M18 4 L19 5"/><path d="M7 5 L8 7 M6 6 L8 6"/></g>,
    clock: <g {...stroke}><circle cx="12" cy="12" r="8"/><path d="M12 7 V12 L15 14"/></g>,
    repeat: <g {...stroke}><path d="M6 9 H16 A4 4 0 0 1 16 17 H8"/><path d="M18 7 L16 9 L18 11"/><path d="M8 19 L6 17 L8 15" transform="translate(-2 0)"/></g>,
    check: <g {...stroke}><path d="M5 12 L10 17 L19 7"/></g>,
    arrowRight: <g {...stroke}><path d="M5 12 H19 M14 7 L19 12 L14 17"/></g>,
  };
  return <svg viewBox="0 0 24 24" width={size} height={size} style={{ display: 'block' }}>{map[name] || map.check}</svg>;
}

/* ---------- Animated rotating popup (used in hero) ---------- */
function RotatingPopup({ words, interval = 3400, compact }) {
  const [i, setI] = useState(0);
  useEffect(() => {
    const t = setInterval(() => setI((x) => (x + 1) % words.length), interval);
    return () => clearInterval(t);
  }, [words.length, interval]);
  const w = words[i];
  return (
    <div key={i} className="pop-in">
      <PopupCard word={w.word} transcription={w.ipa} translation={w.translation} meta={w.meta} compact={compact} />
    </div>
  );
}

/* ---------- Language dropdown ---------- */
// Single shared dropdown reused by all four landings.
// `theme` controls colours so it sits naturally on light / dark / purple / terminal navs.
// Themes: 'light' (default), 'dark', 'purple', 'terminal'.
function LangDropdown({ lang, onLang, theme = 'light' }) {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  const langs = window.WORDY_LANGS || [{ code: 'en', label: 'English', native: 'English', flag: '🇬🇧' }];
  const current = langs.find(l => l.code === lang) || langs[0];

  useEffect(() => {
    if (!open) return;
    const onDoc = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    document.addEventListener('mousedown', onDoc);
    document.addEventListener('keydown', onKey);
    return () => { document.removeEventListener('mousedown', onDoc); document.removeEventListener('keydown', onKey); };
  }, [open]);

  // Theme tokens
  const T = {
    light: {
      bg: 'var(--bg-soft)', border: '1px solid var(--line)', color: 'var(--ink)',
      menuBg: '#fff', menuBorder: '1px solid var(--line)', menuShadow: '0 12px 32px rgba(0,0,0,0.10)',
      hover: 'var(--bg-soft)', activeBg: 'var(--ink)', activeColor: '#fff', radius: 999, mradius: 12,
    },
    dark: {
      bg: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.12)', color: '#fff',
      menuBg: '#1B1A20', menuBorder: '1px solid rgba(255,255,255,0.10)', menuShadow: '0 12px 32px rgba(0,0,0,0.45)',
      hover: 'rgba(255,255,255,0.06)', activeBg: '#fff', activeColor: 'var(--ink)', radius: 999, mradius: 12,
    },
    purple: {
      bg: '#F5F2FF', border: '1px solid #E5DDFB', color: '#5B21B6',
      menuBg: '#fff', menuBorder: '1px solid #E5DDFB', menuShadow: '0 12px 32px rgba(91,33,182,0.14)',
      hover: '#F5F2FF', activeBg: '#7C3AED', activeColor: '#fff', radius: 999, mradius: 12,
    },
    terminal: {
      bg: 'transparent', border: '1.5px solid #1A1814', color: '#1A1814',
      menuBg: '#FAF6EC', menuBorder: '1.5px solid #1A1814', menuShadow: '4px 4px 0 0 #1A1814',
      hover: '#F0EAD8', activeBg: '#1A1814', activeColor: '#FAF6EC', radius: 2, mradius: 2,
    },
  }[theme] || {};

  const isMono = theme === 'terminal';
  const fontFam = isMono ? 'var(--font-mono)' : 'var(--font-mono)';

  return (
    <div ref={ref} style={{ position: 'relative', display: 'inline-block' }}>
      <button
        onClick={() => setOpen(o => !o)}
        aria-haspopup="listbox"
        aria-expanded={open}
        style={{
          display: 'inline-flex', alignItems: 'center', gap: 8,
          padding: '6px 10px 6px 12px',
          background: T.bg, border: T.border, color: T.color,
          borderRadius: T.radius,
          fontSize: 12, fontWeight: 600, fontFamily: fontFam,
          letterSpacing: '0.06em', cursor: 'pointer',
          lineHeight: 1.2,
        }}
      >
        <span>{current.code.toUpperCase()}</span>
        <svg width="10" height="10" viewBox="0 0 12 12" aria-hidden="true"
          style={{ transition: 'transform 0.18s', transform: open ? 'rotate(180deg)' : 'none' }}>
          <path d="M2 4 L6 8 L10 4" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
      </button>
      {open && (
        <ul role="listbox" style={{
          position: 'absolute', top: 'calc(100% + 8px)', right: 0,
          minWidth: 200,
          background: T.menuBg, border: T.menuBorder, borderRadius: T.mradius,
          boxShadow: T.menuShadow,
          padding: 6, margin: 0, listStyle: 'none',
          zIndex: 60, fontFamily: 'var(--font-sans)',
        }}>
          {langs.map(l => {
            const active = l.code === lang;
            return (
              <li key={l.code} role="option" aria-selected={active}>
                <button
                  onClick={() => { onLang(l.code); setOpen(false); }}
                  style={{
                    width: '100%', textAlign: 'left',
                    display: 'flex', alignItems: 'center', gap: 10,
                    padding: '8px 10px',
                    background: active ? T.activeBg : 'transparent',
                    color: active ? T.activeColor : T.color,
                    border: 'none', borderRadius: isMono ? 0 : 8,
                    fontSize: 13, fontFamily: 'var(--font-sans)', fontWeight: active ? 600 : 500,
                    cursor: 'pointer',
                  }}
                  onMouseEnter={(e) => { if (!active) e.currentTarget.style.background = T.hover; }}
                  onMouseLeave={(e) => { if (!active) e.currentTarget.style.background = 'transparent'; }}
                >
                  <span aria-hidden="true" style={{ fontSize: 16, lineHeight: 1 }}>{l.flag}</span>
                  <span style={{ flex: 1 }}>{l.native}</span>
                  <span style={{
                    fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.08em',
                    opacity: active ? 1 : 0.5,
                  }}>{l.code.toUpperCase()}</span>
                </button>
              </li>
            );
          })}
        </ul>
      )}
    </div>
  );
}

/* ---------- Export to global scope for other scripts ---------- */
Object.assign(window, {
  WordyMark, WordyLogo, WordyBrandLogo, PopupCard, DesktopWithPopup, Eyebrow, Section, LineIcon, RotatingPopup, LangDropdown,
});
