// feedback.jsx — Eventfeedback (sandared.se/feedback)
// Renderas av app.jsx när URL:ens path är /feedback. Kopplas till ett event
// via admin-panelen (fliken Feedback). Återanvänder TipsShell (tipspromenad.jsx)
// och TIPS_EVENTS (data.jsx).

const FEEDBACK_KATEGORIER = [
  ['plats',     'Platsen'],
  ['tid',       'Tiden'],
  ['evenemang', 'Evenemanget'],
  ['info',      'Information från SINT'],
];

// ─── Betygsrad 1–5 (på forest-bakgrund) ─────────────────────────────────
// Definieras utanför FeedbackPage så att komponent-typen är stabil.
function FeedbackBetygRad({ label, value, onChange, accent }) {
  const T = SITE_TOKENS;
  return (
    <div style={{ marginTop: 16 }}>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 10, marginBottom: 8 }}>
        <span style={{ fontSize: 14.5, fontWeight: 600, color: T.cream }}>{label}</span>
        <span style={{ fontSize: 12, color: T.cream + '99' }}>{value ? `${value} av 5` : '1 = dåligt · 5 = toppen'}</span>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 8 }}>
        {[1, 2, 3, 4, 5].map(n => {
          const active = value === n;
          const filled = value >= n;
          return (
            <button
              type="button" key={n} onClick={() => onChange(n)}
              style={{ height: 48, borderRadius: 12, border: 0, cursor: 'pointer', fontFamily: 'Bricolage Grotesque', fontSize: 18, fontWeight: 700, background: filled ? accent : 'rgba(255,255,255,0.08)', color: filled ? '#fff' : T.cream + 'aa', boxShadow: active ? `0 0 0 2px ${T.cream}` : filled ? 'none' : `inset 0 0 0 1.5px ${T.cream}33`, transition: 'all .12s' }}
            >
              {n}
            </button>
          );
        })}
      </div>
    </div>
  );
}

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

  const [cfg, setCfg]         = React.useState(null); // { open, event }
  const [failed, setFailed]   = React.useState(false);
  const [betyg, setBetyg]     = React.useState({ plats: 0, tid: 0, evenemang: 0, info: 0 });
  const [text, setText]       = React.useState('');
  const [sending, setSending] = React.useState(false);
  const [error, setError]     = React.useState('');
  const [done, setDone]       = React.useState(false);

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

  React.useEffect(() => {
    API.get('feedback').then(setCfg).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 complete = FEEDBACK_KATEGORIER.every(([k]) => betyg[k] >= 1);

  const submit = async (e) => {
    e.preventDefault();
    if (!complete || sending) return;
    setSending(true);
    setError('');
    try {
      await API.post('feedback', { betyg, text: text.trim() });
      setDone(true);
      window.scrollTo(0, 0);
    } catch (err) {
      setError((err && err.body && err.body.error) || 'Något gick fel när feedbacken skulle skickas. Försök igen.');
    } finally {
      setSending(false);
    }
  };

  if (failed || (cfg && !cfg.open)) {
    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 }}>Feedback</div>
          <h1 style={{ fontSize: compact ? 26 : 32, color: T.cream }}>Feedbacken är stängd just nu.</h1>
          <p style={{ fontSize: 15, color: T.cream + 'cc', marginTop: 14, lineHeight: 1.55 }}>
            Vi öppnar för feedback i samband med våra event — tack för att du vill hjälpa oss bli bättre!
          </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 (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 feedback! ❤️</h1>
            <p style={{ fontSize: 15.5, color: T.cream + 'cc', marginTop: 16, lineHeight: 1.6, maxWidth: 420, marginLeft: 'auto', marginRight: 'auto' }}>
              Dina svar hjälper oss att göra {evInfo.title} ännu bättre nästa år. Vi ses då!
            </p>
            <a href="/" className="btn btn-secondary" style={{ marginTop: 26 }}>Till startsidan</a>
          </div>
        </div>
      </TipsShell>
    );
  }

  // ── Formulär ──
  return (
    <TipsShell compact={compact}>
      <div style={{ textAlign: 'center', marginBottom: compact ? 24 : 32 }}>
        <div style={{ width: compact ? 130 : 160, height: compact ? 130 : 160, borderRadius: '50%', background: evInfo.tint, display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 18px' }}>
          {Illu && <Illu size={compact ? 98 : 122}/>}
        </div>
        <div className="chip" style={{ marginBottom: 14 }}>
          <span className="chip-dot" style={{ background: accent }}/>
          {evInfo.title}
        </div>
        <h1 style={{ fontSize: compact ? 32 : 46, lineHeight: 1.05, fontWeight: 700, letterSpacing: '-0.03em' }}>Vad tyckte du?</h1>
        <p style={{ fontSize: compact ? 15 : 17, color: T.ink2, marginTop: 14, lineHeight: 1.55, maxWidth: 460, marginLeft: 'auto', marginRight: 'auto' }}>
          Tack för att du var med på {evInfo.title}! Betygsätt dagen på en minut — dina svar hjälper oss att göra nästa år ännu bättre.
        </p>
      </div>

      <form onSubmit={submit} 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: 6 }}>Betygsätt 1–5</div>
          <h2 style={{ fontSize: compact ? 22 : 26, color: T.cream }}>Hur upplevde du dagen?</h2>

          {FEEDBACK_KATEGORIER.map(([k, label]) => (
            <FeedbackBetygRad key={k} label={label} value={betyg[k]} onChange={n => setBetyg(b => ({ ...b, [k]: n }))} accent={accent}/>
          ))}

          <div style={{ marginTop: 24, paddingTop: 20, borderTop: `1px solid ${T.cream}22` }}>
            <label style={{ display: 'block', fontSize: 11, fontWeight: 600, color: T.cream + 'cc', marginBottom: 7, letterSpacing: '0.06em', textTransform: 'uppercase' }}>
              Vad kan vi göra bättre tills nästa år?
            </label>
            <textarea
              className="dark-field" rows={5} value={text} maxLength={2000}
              onChange={e => setText(e.target.value)}
              placeholder="Skriv gärna både ris och ros — allt hjälper oss framåt…"
              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', resize: 'vertical', boxShadow: `inset 0 0 0 1.5px ${T.cream}22`, boxSizing: 'border-box' }}
            />
          </div>

          {error && (
            <div style={{ marginTop: 16, 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" disabled={!complete || sending} className="btn btn-primary"
            style={{ width: '100%', justifyContent: 'center', marginTop: 20, background: complete ? accent : 'rgba(255,255,255,0.18)', padding: '17px 24px', fontSize: 16, color: '#fff', opacity: sending ? 0.7 : 1, cursor: complete ? 'pointer' : 'default' }}>
            {sending ? 'Skickar…' : complete ? 'Skicka min feedback →' : 'Sätt betyg på alla fyra delar först'}
          </button>
          <div style={{ fontSize: 12, color: T.cream + '99', marginTop: 12, textAlign: 'center', lineHeight: 1.5 }}>
            Svaren är anonyma och används bara för att förbättra våra event.
          </div>
        </div>
      </form>
    </TipsShell>
  );
}

Object.assign(window, { FeedbackPage });
