// tipspromenad.jsx — Tipspromenad-app (sandared.se/tipspromenad)
// Renderas av app.jsx när URL:ens path är /tipspromenad.
// Återanvänder EventTopBar/EventFooter (event.jsx), DarkField (signup.jsx)
// och TIPS_EVENTS (data.jsx). Konfiguration hämtas från /api/tipspromenad.

const TIPS_VAL = ['1', 'X', '2'];
const TIPS_DRAFT_KEY = 'sint_tips_draft';

function tipsDoneKey(roundId, kategori) { return `sint_tips_done_${roundId}_${kategori}`; }
function loadTipsDraft() { try { return JSON.parse(localStorage.getItem(TIPS_DRAFT_KEY)); } catch (e) { return null; } }
function saveTipsDraft(d) { try { localStorage.setItem(TIPS_DRAFT_KEY, JSON.stringify(d)); } catch (e) {} }
function clearTipsDraft() { try { localStorage.removeItem(TIPS_DRAFT_KEY); } catch (e) {} }

// ─── Kategori-väljare (Vuxen/Barn) på forest-bakgrund ──────────────────
function TipsKategoriVal({ kategori, setKategori, accent }) {
  const T = SITE_TOKENS;
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
      {[['vuxen', 'Vuxen', '🧑'], ['barn', 'Barn', '🧒']].map(([id, label, emoji]) => {
        const active = kategori === id;
        return (
          <button type="button" key={id} onClick={() => setKategori(id)} style={{ padding: '14px 16px', borderRadius: 12, background: active ? T.cream : 'transparent', color: active ? T.ink : T.cream, boxShadow: active ? 'none' : `inset 0 0 0 1.5px ${T.cream}44`, fontWeight: 600, fontSize: 14, textAlign: 'left', display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer', border: 0 }}>
            <div style={{ width: 18, height: 18, borderRadius: '50%', background: active ? accent : 'transparent', boxShadow: active ? 'none' : `inset 0 0 0 1.5px ${T.cream}88`, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              {active && <div style={{ width: 7, height: 7, background: '#fff', borderRadius: '50%' }}/>}
            </div>
            {emoji} {label}
          </button>
        );
      })}
    </div>
  );
}

// ─── Sidskal (topbar + centrerad kolumn + footer) ───────────────────────
// Definieras utanför TipspromenadPage — annars återskapas komponent-typen
// vid varje render och inputfälten tappar fokus.
function TipsShell({ compact, children }) {
  const T = SITE_TOKENS;
  return (
    <div style={{ background: T.cream, minHeight: '100vh', display: 'flex', flexDirection: 'column' }}>
      <EventTopBar compact={compact}/>
      <div style={{ flex: 1, width: '100%', maxWidth: 640, margin: '0 auto', padding: compact ? '26px 20px 48px' : '48px 24px 72px' }}>
        {children}
      </div>
      <EventFooter compact={compact}/>
    </div>
  );
}

// ─── Hela tipspromenad-sidan ────────────────────────────────────────────
function TipspromenadPage({ isMobile }) {
  const T = SITE_TOKENS;
  const compact = isMobile;

  const [cfg, setCfg]       = React.useState(null);   // { active, event, roundId, vuxen:{count}, barn:{count} }
  const [failed, setFailed] = React.useState(false);
  const [step, setStep]     = React.useState('intro'); // intro | quiz | done

  const [kategori, setKategori] = React.useState('vuxen');
  const [namn, setNamn]         = React.useState('');
  const [mobil, setMobil]       = React.useState('');
  const [svar, setSvar]         = React.useState([]);
  const [skilje, setSkilje]     = React.useState('');
  const [sending, setSending]   = React.useState(false);
  const [error, setError]       = React.useState('');

  React.useEffect(() => {
    const prev = document.title;
    document.title = 'Tipspromenad · Sandareds Intresseförening';
    return () => { document.title = prev; };
  }, []);

  // Hämta aktuell omgång + återuppta ev. påbörjat/inlämnat deltagande
  React.useEffect(() => {
    API.get('tipspromenad').then(c => {
      setCfg(c);
      if (!c || !c.active) return;
      const draft = loadTipsDraft();
      if (draft && draft.roundId === c.roundId && draft.kategori && c[draft.kategori]) {
        setKategori(draft.kategori);
        setNamn(draft.namn || '');
        setMobil(draft.mobil || '');
        setSvar(Array.isArray(draft.svar) ? draft.svar : []);
        setSkilje(draft.skilje || '');
        if (draft.submitted) setStep('done');
        else if (draft.started) setStep('quiz');
      }
    }).catch(() => setFailed(true));
  }, []);

  const evInfo = cfg ? (TIPS_EVENTS[cfg.event] || TIPS_EVENTS.sandaredsdagen) : null;
  const accent = evInfo ? evInfo.accent : T.coral;
  const Illu   = evInfo ? window[evInfo.illu] : null;
  const count  = cfg && cfg[kategori] ? cfg[kategori].count : 0;
  const answered = svar.filter(s => TIPS_VAL.includes(s)).length;
  const complete = count > 0 && answered === count && skilje.trim().length > 0;

  const persistDraft = (patch) => {
    saveTipsDraft({ roundId: cfg.roundId, kategori, namn, mobil, svar, skilje, started: true, submitted: false, ...patch });
  };

  const start = (e) => {
    e.preventDefault();
    setError('');
    if (!namn.trim() || !mobil.trim()) { setError('Fyll i både namn och mobilnummer.'); return; }
    if (localStorage.getItem(tipsDoneKey(cfg.roundId, kategori))) {
      setError('Det här numret har redan lämnat in svar i den här kategorin på den här enheten.');
      return;
    }
    setSvar(Array.from({ length: count }, () => ''));
    setSkilje('');
    setStep('quiz');
    saveTipsDraft({ roundId: cfg.roundId, kategori, namn, mobil, svar: [], skilje: '', started: true, submitted: false });
    window.scrollTo(0, 0);
  };

  const pick = (i, val) => {
    const next = svar.slice();
    next[i] = val;
    setSvar(next);
    persistDraft({ svar: next });
  };

  const submit = async () => {
    if (!complete || sending) return;
    setSending(true);
    setError('');
    try {
      await API.post('tipspromenad', { namn: namn.trim(), mobil: mobil.trim(), kategori, svar, skilje: skilje.trim() });
      try { localStorage.setItem(tipsDoneKey(cfg.roundId, kategori), namn.trim()); } catch (e) {}
      persistDraft({ submitted: true });
      setStep('done');
      window.scrollTo(0, 0);
    } catch (e) {
      setError((e && e.body && e.body.error) || 'Något gick fel när svaren skulle skickas. Försök igen.');
    } finally {
      setSending(false);
    }
  };

  const restart = () => {
    clearTipsDraft();
    setStep('intro');
    setSvar([]);
    setSkilje('');
    setError('');
    window.scrollTo(0, 0);
  };

  // ── Laddning / fel / stängd ──
  if (failed || (cfg && !cfg.active)) {
    return (
      <TipsShell compact={compact}>
        <div style={{ background: T.forest, color: T.cream, borderRadius: 24, padding: compact ? '36px 24px' : '52px 40px', textAlign: 'center' }}>
          <div style={{ width: 64, height: 64, borderRadius: '50%', background: 'rgba(255,255,255,0.12)', margin: '0 auto 22px', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke={T.sun} strokeWidth="2" strokeLinecap="round">
              <circle cx="12" cy="12" r="10"/><path d="M12 6 V12 L16 14"/>
            </svg>
          </div>
          <div className="eyebrow" style={{ color: T.sun, marginBottom: 12 }}>Tipspromenad</div>
          <h1 style={{ fontSize: compact ? 26 : 32, color: T.cream }}>Ingen tipspromenad pågår just nu.</h1>
          <p style={{ fontSize: 15, color: T.cream + 'cc', marginTop: 14, lineHeight: 1.55 }}>
            Håll utkik i kalendern — vi öppnar tipspromenaden i samband med våra event.
          </p>
          <a href="/" className="btn btn-secondary" style={{ marginTop: 24 }}>Till startsidan</a>
        </div>
      </TipsShell>
    );
  }

  if (!cfg) {
    return (
      <TipsShell compact={compact}>
        <div style={{ textAlign: 'center', padding: '80px 0', color: T.muted, fontSize: 14 }}>Laddar…</div>
      </TipsShell>
    );
  }

  // ── Tack-vy ──
  if (step === 'done') {
    return (
      <TipsShell compact={compact}>
        <div style={{ background: T.forest, color: T.cream, borderRadius: 24, padding: compact ? '40px 24px' : '56px 44px', textAlign: 'center', position: 'relative', overflow: 'hidden' }}>
          <div style={{ position: 'absolute', top: -90, right: -90, width: 260, height: 260, borderRadius: '50%', background: accent, opacity: 0.18 }}/>
          <div style={{ position: 'relative' }}>
            <div style={{ width: 72, height: 72, borderRadius: '50%', background: accent, margin: '0 auto 24px', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <svg width="36" height="36" viewBox="0 0 24 24"><path d="M5 13 L10 18 L20 7" stroke="#fff" strokeWidth="3" fill="none" strokeLinecap="round"/></svg>
            </div>
            <h1 style={{ fontSize: compact ? 28 : 34, color: T.cream }}>Tack för din medverkan{namn.trim() ? `, ${namn.trim().split(' ')[0]}` : ''}!</h1>
            <p style={{ fontSize: 15.5, color: T.cream + 'cc', marginTop: 16, lineHeight: 1.6, maxWidth: 420, marginLeft: 'auto', marginRight: 'auto' }}>
              Dina svar är inlämnade. Vi rättar alla svar när tipspromenaden är avslutad och meddelar vinnarna. Lycka till! 🍀
            </p>
            <div style={{ display: 'flex', gap: 10, justifyContent: 'center', flexWrap: 'wrap', marginTop: 28 }}>
              <a href="/" className="btn btn-secondary">Till startsidan</a>
              <button onClick={restart} className="btn" style={{ background: 'rgba(255,255,255,0.1)', color: T.cream, boxShadow: `inset 0 0 0 1.5px ${T.cream}44` }}>
                Lämna in för fler (t.ex. barn)
              </button>
            </div>
          </div>
        </div>
      </TipsShell>
    );
  }

  // ── Frågevy ──
  if (step === 'quiz') {
    return (
      <TipsShell compact={compact}>
        {/* Progress-huvud */}
        <div className="card" style={{ padding: compact ? 18 : 22, marginBottom: 18, position: 'sticky', top: compact ? 60 : 80, zIndex: 20 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            <div style={{ width: 46, height: 46, borderRadius: 12, background: evInfo.tint, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              {Illu && <Illu size={36}/>}
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontFamily: 'Bricolage Grotesque', fontSize: 16, fontWeight: 700 }}>
                Tipspromenad · {kategori === 'barn' ? 'Barn' : 'Vuxen'}
              </div>
              <div style={{ fontSize: 12.5, color: T.muted }}>{namn.trim()} · {answered} av {count} frågor besvarade</div>
            </div>
          </div>
          <div style={{ height: 8, borderRadius: 999, background: T.line, overflow: 'hidden', marginTop: 12 }}>
            <div style={{ height: '100%', borderRadius: 999, width: `${count ? (answered / count) * 100 : 0}%`, background: accent, transition: 'width .3s' }}/>
          </div>
        </div>

        {/* Frågor */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {Array.from({ length: count }, (_, i) => (
            <div key={i} className="card" style={{ padding: compact ? '16px 16px' : '18px 22px' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <div style={{ width: 34, height: 34, borderRadius: '50%', background: svar[i] ? accent : T.cream2, color: svar[i] ? '#fff' : T.ink2, display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'Bricolage Grotesque', fontWeight: 700, fontSize: 15, flexShrink: 0, transition: 'background .15s' }}>
                  {i + 1}
                </div>
                <div style={{ fontWeight: 600, fontSize: 15, flex: 1 }}>Fråga {i + 1}</div>
                {svar[i] && (
                  <svg width="18" height="18" viewBox="0 0 24 24"><path d="M5 13 L10 18 L20 7" stroke={accent} strokeWidth="2.5" fill="none" strokeLinecap="round"/></svg>
                )}
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8, marginTop: 12 }}>
                {TIPS_VAL.map(val => {
                  const active = svar[i] === val;
                  return (
                    <button key={val} onClick={() => pick(i, val)} style={{ height: 52, borderRadius: 12, border: 0, cursor: 'pointer', fontFamily: 'Bricolage Grotesque', fontSize: 20, fontWeight: 700, background: active ? accent : T.cream, color: active ? '#fff' : T.ink, boxShadow: active ? 'none' : `inset 0 0 0 1.5px ${T.line}`, transition: 'all .12s' }}>
                      {val}
                    </button>
                  );
                })}
              </div>
            </div>
          ))}

          {/* Skiljefråga */}
          <div className="card" style={{ padding: compact ? '18px 16px' : '20px 22px', boxShadow: `inset 0 0 0 1.5px ${accent}55` }}>
            <div className="eyebrow" style={{ color: accent, marginBottom: 6 }}>Skiljefrågan</div>
            <div style={{ fontWeight: 600, fontSize: 15 }}>Ditt svar på skiljefrågan</div>
            <p style={{ fontSize: 13, color: T.muted, marginTop: 6, lineHeight: 1.5 }}>
              Skiljefrågan hittar du vid sista stationen. Vid lika många rätt avgör den vem som vinner.
            </p>
            <input
              value={skilje}
              onChange={e => { setSkilje(e.target.value); persistDraft({ skilje: e.target.value }); }}
              placeholder="Skriv ditt svar här…"
              style={{ width: '100%', marginTop: 12, padding: '14px 16px', borderRadius: 12, border: 0, background: T.cream, boxShadow: `inset 0 0 0 1.5px ${T.line}`, fontSize: 15, fontFamily: 'inherit', color: T.ink, outline: 'none', boxSizing: 'border-box' }}
              onFocus={e => { e.target.style.boxShadow = `inset 0 0 0 2px ${accent}`; }}
              onBlur={e => { e.target.style.boxShadow = `inset 0 0 0 1.5px ${T.line}`; }}
            />
          </div>

          {/* Skicka in */}
          {error && (
            <div style={{ padding: '13px 16px', borderRadius: 12, background: '#FDE8E8', color: '#CC3333', fontSize: 13.5, fontWeight: 600 }}>{error}</div>
          )}
          <button
            onClick={submit}
            disabled={!complete || sending}
            className="btn btn-primary"
            style={{ width: '100%', justifyContent: 'center', padding: '18px 24px', fontSize: 16, background: complete ? accent : T.muted, color: '#fff', opacity: sending ? 0.7 : 1, cursor: complete ? 'pointer' : 'default' }}
          >
            {sending ? 'Skickar…' : complete ? 'Skicka in mina svar →' : `Besvara alla frågor först (${answered}/${count}${skilje.trim() ? '' : ' + skiljefrågan'})`}
          </button>
          <button onClick={restart} style={{ background: 'transparent', border: 0, color: T.muted, fontSize: 13, cursor: 'pointer', padding: 8, textDecoration: 'underline' }}>
            Avbryt och börja om
          </button>
        </div>
      </TipsShell>
    );
  }

  // ── Startvy (intro + registrering) ──
  return (
    <TipsShell compact={compact}>
      {/* Hero */}
      <div style={{ textAlign: 'center', marginBottom: compact ? 26 : 36 }}>
        <div style={{ width: compact ? 150 : 190, height: compact ? 150 : 190, borderRadius: '50%', background: evInfo.tint, display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 20px' }}>
          {Illu && <Illu size={compact ? 112 : 145}/>}
        </div>
        <div className="chip" style={{ marginBottom: 14 }}>
          <span className="chip-dot" style={{ background: accent }}/>
          I samband med {evInfo.title}
        </div>
        <h1 style={{ fontSize: compact ? 38 : 54, lineHeight: 1, fontWeight: 700, letterSpacing: '-0.03em' }}>Tipspromenad</h1>
        <p style={{ fontSize: compact ? 15 : 17, color: T.ink2, marginTop: 14, lineHeight: 1.55, maxWidth: 460, marginLeft: 'auto', marginRight: 'auto' }}>
          Gå promenaden, läs frågorna vid varje station och svara med 1, X eller 2 direkt i mobilen. Flest rätt vinner — skiljefrågan avgör vid lika!
        </p>
      </div>

      {/* Så funkar det */}
      <div className="card" style={{ padding: compact ? 20 : 26, marginBottom: 18 }}>
        <div className="eyebrow" style={{ marginBottom: 14, color: accent }}>Så funkar det</div>
        {[
          ['1', 'Fyll i namn och mobilnummer nedan och välj Vuxen eller Barn.'],
          ['2', `Följ promenaden och svara 1, X eller 2 på varje fråga (${cfg.vuxen.count} st för vuxna, ${cfg.barn.count} st för barn).`],
          ['3', 'Svara på skiljefrågan vid sista stationen och skicka in dina svar.'],
        ].map(([n, text]) => (
          <div key={n} style={{ display: 'flex', gap: 14, alignItems: 'flex-start', marginBottom: 12 }}>
            <div style={{ width: 28, height: 28, borderRadius: '50%', background: accent + '22', color: accent, display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'Bricolage Grotesque', fontWeight: 700, fontSize: 14, flexShrink: 0 }}>{n}</div>
            <p style={{ fontSize: 14, color: T.ink2, lineHeight: 1.55, margin: 0, paddingTop: 4 }}>{text}</p>
          </div>
        ))}
        <div style={{ fontSize: 12.5, color: T.muted, marginTop: 4, paddingTop: 12, borderTop: `1px solid ${T.line}` }}>
          Ett deltagande per mobilnummer och kategori. Vinnarna kontaktas efter rättning — 1:a, 2:a och 3:e pris i både vuxen- och barnklassen.
        </div>
      </div>

      {/* Startformulär */}
      <form onSubmit={start} style={{ background: T.forest, color: T.cream, borderRadius: 24, padding: compact ? 22 : 32, position: 'relative', overflow: 'hidden' }}>
        <div style={{ position: 'absolute', top: -80, right: -80, width: 220, height: 220, borderRadius: '50%', background: accent, opacity: 0.18 }}/>
        <div style={{ position: 'relative' }}>
          <div className="eyebrow" style={{ color: T.sun, marginBottom: 10 }}>Starta tipspromenaden</div>
          <h2 style={{ fontSize: compact ? 22 : 26, color: T.cream }}>Vem går promenaden?</h2>
          <div style={{ marginTop: 18 }}>
            <TipsKategoriVal kategori={kategori} setKategori={setKategori} accent={accent}/>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr', gap: 12, marginTop: 14 }}>
            <div>
              <label style={{ display: 'block', fontSize: 11, fontWeight: 600, color: T.cream + 'cc', marginBottom: 7, letterSpacing: '0.06em', textTransform: 'uppercase' }}>Namn <span style={{ color: T.sun }}>*</span></label>
              <input className="dark-field" value={namn} onChange={e => setNamn(e.target.value)} placeholder="Anna Andersson" required
                style={{ width: '100%', padding: '14px 16px', borderRadius: 12, border: 0, background: 'rgba(255,255,255,0.08)', color: T.cream, fontSize: 15, fontFamily: 'inherit', outline: 'none', boxShadow: `inset 0 0 0 1.5px ${T.cream}22`, boxSizing: 'border-box' }}/>
            </div>
            <div>
              <label style={{ display: 'block', fontSize: 11, fontWeight: 600, color: T.cream + 'cc', marginBottom: 7, letterSpacing: '0.06em', textTransform: 'uppercase' }}>Mobilnummer <span style={{ color: T.sun }}>*</span></label>
              <input className="dark-field" value={mobil} onChange={e => setMobil(e.target.value)} placeholder="070-123 45 67" type="tel" required
                style={{ width: '100%', padding: '14px 16px', borderRadius: 12, border: 0, background: 'rgba(255,255,255,0.08)', color: T.cream, fontSize: 15, fontFamily: 'inherit', outline: 'none', boxShadow: `inset 0 0 0 1.5px ${T.cream}22`, boxSizing: 'border-box' }}/>
            </div>
          </div>
          {error && (
            <div style={{ marginTop: 14, padding: '12px 14px', borderRadius: 12, background: 'rgba(0,0,0,0.22)', color: T.sun, fontSize: 13.5, fontWeight: 600 }}>{error}</div>
          )}
          <button type="submit" className="btn btn-primary" style={{ width: '100%', justifyContent: 'center', marginTop: 18, background: accent, padding: '17px 24px', fontSize: 16, color: '#fff' }}>
            Starta tipspromenaden →
          </button>
          <div style={{ fontSize: 12, color: T.cream + '99', marginTop: 12, textAlign: 'center', lineHeight: 1.5 }}>
            Mobilnumret används bara för att kunna kontakta vinnarna och för att varje nummer bara ska kunna delta en gång.
          </div>
        </div>
      </form>
    </TipsShell>
  );
}

Object.assign(window, { TipspromenadPage });
