// Interactive name-drop demo: add names, hit "next" to see how Zuipie picks targets.
const { useState, useMemo, useRef } = React;

const DEMO_QUESTIONS = {
  nl: [
    { body: "Neem per zwart kledingstuk 5 slokken.", shots: "(een paar sokken telt als 2)", target: "everybody" },
    { body: "neem per tatoeage 8 slokken.", shots: "(max 35 slokken)", target: "player" },
    { body: "Iedereen wiens telefoon minder dan 20% batterij heeft, neemt 4 slokken.", shots: "Check je telefoon nu", target: "everybody" },
    { body: "deel je aantal Instagram-volgers door 100. Dat is je aantal slokken.", shots: "(max 20 slokken)", target: "player" },
    { body: "Heb je een bril of lenzen? Neem 4 slokken.", shots: "Contactlenzen tellen ook", target: "everybody" },
    { body: "vertel je gênantste schoolverhaal of neem 10 slokken.", shots: "De groep beslist", target: "player" },
    { body: "Ooit met een kater op werk gekomen? Neem 5 slokken.", shots: "Eerlijk antwoorden", target: "both" },
    { body: "deel het aantal slokken uit als het aantal letters in je voornaam.", shots: "Korte naam? Geluk gehad.", target: "player" }
  ],
  en: [
    { body: "Take 5 sips for every black item of clothing.", shots: "(a pair of socks counts as 2)", target: "everybody" },
    { body: "take 8 sips for every tattoo you have.", shots: "(max 35 sips)", target: "player" },
    { body: "Anyone whose phone is below 20% battery: 4 sips.", shots: "Check your phone now", target: "everybody" },
    { body: "divide your Instagram followers by 100. That's your sips.", shots: "(max 20 sips)", target: "player" },
    { body: "Do you wear glasses or contacts? Take 4 sips.", shots: "Contacts count too", target: "everybody" },
    { body: "tell your most embarrassing school story or take 10 sips.", shots: "The group decides", target: "player" },
    { body: "Ever been to work with a hangover? Take 5 sips.", shots: "Answer honestly", target: "both" },
    { body: "hand out a sip for every letter in your first name.", shots: "Short name? Lucky you.", target: "player" }
  ]
};

const PRESET_NAMES = ["Mark", "Sarah", "Tom", "Lisa", "Bram", "Eva", "Daan"];

function t(key, lang) {
  return (window.ZUIPIE_I18N?.[lang] || window.ZUIPIE_I18N?.nl || {})[key] || key;
}

function Demo() {
  const [lang, setLang] = useState(document.documentElement.lang || 'nl');
  const [names, setNames] = useState(["Mark", "Sarah", "Tom"]);
  const [input, setInput] = useState("");
  const [idx, setIdx] = useState(0);
  const [flash, setFlash] = useState(false);
  const [overridePlayer, setOverridePlayer] = useState(null);
  const inputRef = useRef(null);

  // Listen for language changes from the i18n system
  React.useEffect(() => {
    const handler = () => setLang(document.documentElement.lang || 'nl');
    const mo = new MutationObserver(handler);
    mo.observe(document.documentElement, { attributes: true, attributeFilter: ['lang'] });
    return () => mo.disconnect();
  }, []);

  const questions = DEMO_QUESTIONS[lang] || DEMO_QUESTIONS.nl;
  const q = questions[idx % questions.length];

  const renderedName = useMemo(() => {
    if (q.target === 'everybody') return null;
    if (q.target === 'player') {
      return overridePlayer || (names.length ? names[Math.floor(Math.random() * names.length)] : null);
    }
    // both: 50/50
    if (overridePlayer) return overridePlayer;
    return Math.random() > 0.5 && names.length ? names[Math.floor(Math.random() * names.length)] : null;
  }, [idx, overridePlayer]);

  function addName(n) {
    const trimmed = (n || "").trim();
    if (!trimmed) return;
    if (names.some(x => x.toLowerCase() === trimmed.toLowerCase())) return;
    setNames([...names, trimmed]);
    setInput("");
  }

  function removeName(n) {
    setNames(names.filter(x => x !== n));
  }

  function next() {
    setOverridePlayer(null);
    setIdx(i => i + 1);
    setFlash(true);
    setTimeout(() => setFlash(false), 360);
  }

  const empty = names.length === 0;

  return (
    <div className="demo-stage">
      <div className="demo-label">{t('demo.label', lang)}</div>
      <div className="name-input-row">
        <input
          ref={inputRef}
          value={input}
          onChange={e => setInput(e.target.value)}
          onKeyDown={e => { if (e.key === 'Enter') { e.preventDefault(); addName(input); } }}
          placeholder={t('demo.placeholder', lang)}
          maxLength={16}
        />
        <button onClick={() => addName(input)}>{t('demo.add', lang)}</button>
      </div>
      <div className="name-chips">
        {names.length === 0 && (
          <div style={{color:'var(--text-low)', fontSize:13, fontWeight:700, fontStyle:'italic', alignSelf:'center'}}>
            {PRESET_NAMES.slice(0,3).map(n => (
              <button
                key={n}
                onClick={() => addName(n)}
                style={{background:'transparent', border:'1.5px dashed var(--text-low)', borderRadius:999, padding:'5px 11px', marginRight:6, color:'var(--text-mute)', fontFamily:'Fredoka One', fontSize:13, cursor:'pointer'}}
              >+ {n}</button>
            ))}
          </div>
        )}
        {names.map(n => (
          <span key={n} className="name-chip">
            {n}
            <button onClick={() => removeName(n)} aria-label="remove">×</button>
          </span>
        ))}
      </div>

      <div className={`demo-qcard ${flash ? 'flash' : ''}`} key={idx}>
        {renderedName && <span className="pill">{renderedName.toUpperCase()},</span>}
        <div className="body">
          {empty && q.target !== 'everybody'
            ? <span style={{color:'var(--text-low)', fontStyle:'italic', fontSize:18}}>{t('demo.empty', lang)}</span>
            : (renderedName ? q.body : q.body.charAt(0).toUpperCase() + q.body.slice(1))}
        </div>
        <div className="shots">{q.shots}</div>
      </div>

      <button className="demo-next" onClick={next}>
        <span>{t('demo.next', lang)}</span>
        <span>→</span>
      </button>
    </div>
  );
}

const demoRoot = document.getElementById('demo-root');
if (demoRoot) {
  ReactDOM.createRoot(demoRoot).render(<Demo />);
}
