// feedback2.jsx — Reader Feedback flow, premium restyle (logic identical to v1).
const { useState: useFState, useEffect: useFEffect } = React;

function Fade({ children }) {
  const [on, setOn] = useFState(false);
  useFEffect(() => { const t = setTimeout(() => setOn(true), 20); return () => clearTimeout(t); }, []);
  return (
    <div style={{ transform: on ? 'translateY(0)' : 'translateY(10px)', transition: 'transform .42s cubic-bezier(.2,.7,.2,1)' }}>{children}</div>
  );
}

function Mark({ size = 13, style = {} }) {
  return <span aria-hidden="true" style={{ color: T.color.accent, fontSize: size, lineHeight: 1, ...style }}>✦</span>;
}

function ThankYou() {
  const [pop, setPop] = useFState(false);
  useFEffect(() => { const t = setTimeout(() => setPop(true), 40); return () => clearTimeout(t); }, []);
  return (
    <Card style={{ padding: '52px 36px 44px', textAlign: 'center' }}>
      <div style={{
        width: 76, height: 76, margin: '0 auto', borderRadius: 100,
        border: '1px solid ' + T.color.accent, background: T.color.accentSoft,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        transform: pop ? 'scale(1)' : 'scale(0.5)', opacity: pop ? 1 : 0,
        transition: 'transform .6s cubic-bezier(.2,1.3,.3,1.1), opacity .4s ease',
      }}>
        <Mark size={26} />
      </div>
      <h2 style={{ fontFamily: T.font.display, fontWeight: 600, fontSize: 34, color: T.color.text, margin: '24px 0 10px', letterSpacing: 0.2 }}>Thank you</h2>
      <p style={{ fontFamily: T.font.body, fontSize: 15.5, lineHeight: 1.65, color: T.color.textSoft, margin: '0 auto', maxWidth: 380 }}>
        Your feedback means the world to us. You're helping shape a book that celebrates what unites us all.
      </p>
      <Divider style={{ margin: '30px auto', maxWidth: 200 }} />
      <div style={{ fontFamily: T.font.head, fontWeight: 800, fontSize: 11, color: T.color.textFaint, letterSpacing: 2, textTransform: 'uppercase' }}>Book of Light</div>
    </Card>
  );
}

function SendFailed({ message, onRetry, onBack }) {
  return (
    <Card style={{ padding: '52px 36px 44px', textAlign: 'center' }}>
      <div style={{
        width: 76, height: 76, margin: '0 auto', borderRadius: 100,
        border: '1px solid ' + T.color.danger, background: 'transparent',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontFamily: T.font.display, fontSize: 32, color: T.color.danger, lineHeight: 1,
      }}>!</div>
      <h2 style={{ fontFamily: T.font.display, fontWeight: 600, fontSize: 32, color: T.color.text, margin: '24px 0 10px', letterSpacing: 0.2 }}>We couldn't send your feedback</h2>
      <p style={{ fontFamily: T.font.body, fontSize: 15.5, lineHeight: 1.65, color: T.color.textSoft, margin: '0 auto 8px', maxWidth: 400 }}>
        Your notes are safe on this device — nothing you wrote has been lost. Please try sending again.
      </p>
      {message && (
        <p style={{ fontFamily: T.font.body, fontSize: 13.5, lineHeight: 1.6, color: T.color.textFaint, margin: '0 auto 26px', maxWidth: 400 }}>{message}</p>
      )}
      <div style={{ display: 'flex', gap: 10, justifyContent: 'center', flexWrap: 'wrap' }}>
        <Btn variant="ghost" onClick={onBack}>← Back to the form</Btn>
        <Btn onClick={onRetry}>Try again <span className="p-arr">→</span></Btn>
      </div>
    </Card>
  );
}

function FeedbackPortal({ initialCode = '', onSubmitted, onAdmin }) {
  const [step, setStep] = useFState(1);
  const [code, setCode] = useFState(initialCode);
  const [name, setName] = useFState('');
  const [email, setEmail] = useFState('');
  const [role, setRole] = useFState('');
  const [rating, setRating] = useFState(0);
  const [prompts, setPrompts] = useFState({ resonated: '', conversation: '', improve: '', favourite: '' });
  const [comments, setComments] = useFState('');
  const [files, setFiles] = useFState([]);
  const [submitting, setSubmitting] = useFState(false);
  const [done, setDone] = useFState(false);
  const [sendError, setSendError] = useFState(null);

  const setPrompt = (k, v) => setPrompts((p) => ({ ...p, [k]: v }));

  const submit = async () => {
    setSubmitting(true);
    setSendError(null);
    const entry = {
      id: uid(), code: code.trim(), name: name.trim(), email: email.trim(), role,
      rating, prompts, comments: comments.trim(), files,
      timestamp: new Date().toISOString(),
    };

    // local copy first — a network failure must never lose the reader's typing
    try {
      const list = (await storage.get(KEYS.feedback)) || [];
      await storage.set(KEYS.feedback, [entry, ...list]);
    } catch (e) { /* the transmission below is what counts */ }

    try {
      const res = await fetch('/api/feedback', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          code: entry.code, name: entry.name, email: entry.email, role: entry.role,
          rating: entry.rating, prompts: entry.prompts, comments: entry.comments,
          timestamp: entry.timestamp,
          files: (files || []).map((f) => ({ name: f.name, type: f.type })),
        }),
      });
      if (!res.ok) {
        let msg = 'The server could not accept it (error ' + res.status + ').';
        try { const d = await res.json(); if (d && d.message) msg = d.message; } catch (e) { /* keep default */ }
        throw new Error(msg);
      }
      setSubmitting(false);
      setDone(true);
      onSubmitted && onSubmitted();
    } catch (e) {
      setSubmitting(false);
      setSendError((e && e.message) || 'We could not reach the server.');
    }
  };

  if (done) return <div style={{ maxWidth: T.maxForm, margin: '0 auto' }}><Fade><ThankYou /></Fade></div>;

  if (sendError) {
    return (
      <div style={{ maxWidth: T.maxForm, margin: '0 auto' }}>
        <Fade><SendFailed message={sendError} onRetry={submit} onBack={() => setSendError(null)} /></Fade>
      </div>
    );
  }

  if (submitting) {
    return (
      <div style={{ maxWidth: T.maxForm, margin: '0 auto' }}>
        <Card style={{ padding: 56, textAlign: 'center' }}>
          <div className="bol-pulse" style={{ fontSize: 30, color: T.color.accent }}>✦</div>
          <div style={{ fontFamily: T.font.head, fontWeight: 700, fontSize: 15, color: T.color.textSoft, marginTop: 16 }}>Saving your feedback…</div>
        </Card>
      </div>
    );
  }

  return (
    <div style={{ maxWidth: T.maxForm, margin: '0 auto' }}>
      <Card style={{ padding: '30px 30px 26px' }}>
        <ProgressBar step={step} total={3} />

        {step === 1 && (
          <Fade key="s1">
            <div style={{ textAlign: 'center', marginBottom: 26 }}>
              <Mark style={{ letterSpacing: 8 }} />
              <h1 style={{ fontFamily: T.font.display, fontWeight: 600, fontSize: 30, lineHeight: 1.2, margin: '10px 0 0', color: T.color.text, letterSpacing: 0.2 }}>
                The First Mistake
              </h1>
              <p style={{ fontFamily: T.font.body, fontSize: 15, lineHeight: 1.65, color: T.color.textSoft, margin: '6px auto 0', maxWidth: 400 }}>
                Book One · Test edition
              </p>
              <p style={{ fontFamily: T.font.body, fontSize: 15, lineHeight: 1.65, color: T.color.textSoft, margin: '12px auto 0', maxWidth: 400 }}>
                Welcome, early reader. This is a private portal for our test copies — your thoughts directly shape the final book.
              </p>
            </div>
            <Input label="Your access code" value={code} onChange={setCode} uppercase placeholder="READER-0042"
              hint="You'll find this printed near the QR code in your copy." />
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, marginTop: -8, marginBottom: 16 }}>
              <button type="button" onClick={() => setCode(TEST_ACCESS_CODE)}
                style={{ fontFamily: T.font.body, fontSize: 12, color: T.color.textFaint, background: 'transparent', border: '1px dashed ' + T.color.border, borderRadius: 100, padding: '5px 12px', cursor: 'pointer' }}>
                Testing? Use {TEST_ACCESS_CODE}
              </button>
            </div>
            <Btn full disabled={!code.trim()} onClick={() => setStep(2)}>Continue <span className="p-arr">→</span></Btn>
          </Fade>
        )}

        {step === 2 && (
          <Fade key="s2">
            <h2 style={{ fontFamily: T.font.display, fontWeight: 600, fontSize: 26, margin: '0 0 6px', color: T.color.text }}>A little about you</h2>
            <p style={{ fontFamily: T.font.body, fontSize: 14.5, color: T.color.textSoft, margin: '0 0 22px' }}>Everything here is optional — share only what you'd like.</p>
            <Input label="Name" value={name} onChange={setName} placeholder="Optional" />
            <Input label="Email" type="email" value={email} onChange={setEmail} placeholder="optional@email.com" />
            <Field label="Your role" hint="Tap to select — tap again to clear.">
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 9, marginTop: 2 }}>
                {ROLES.map((r) => <Pill key={r} selected={role === r} onClick={() => setRole(role === r ? '' : r)}>{r}</Pill>)}
              </div>
            </Field>
            <div style={{ display: 'flex', gap: 10, marginTop: 8 }}>
              <Btn variant="ghost" onClick={() => setStep(1)}>← Back</Btn>
              <Btn full onClick={() => setStep(3)}>Continue <span className="p-arr">→</span></Btn>
            </div>
          </Fade>
        )}

        {step === 3 && (
          <Fade key="s3">
            <h2 style={{ fontFamily: T.font.display, fontWeight: 600, fontSize: 26, margin: '0 0 20px', color: T.color.text }}>Your feedback</h2>
            <Field label="How would you rate the book?">
              <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
                <StarRating value={rating} onChange={setRating} />
                {rating > 0 && <span style={{ fontFamily: T.font.body, fontSize: 14, color: T.color.textSoft }}>{rating} / 5</span>}
              </div>
            </Field>
            {PROMPTS.map((p) => (
              <CountedTextarea key={p.key} label={p.label} value={prompts[p.key]} onChange={(v) => setPrompt(p.key, v)} max={p.max} rows={3} placeholder="Optional" />
            ))}
            <CountedTextarea label="General comments" value={comments} onChange={setComments} max={1000} rows={4} placeholder="Anything else you'd love to share…" />
            <Field label="Photos or notes (optional)">
              <FileUploader files={files} onChange={setFiles} />
            </Field>
            <div style={{ display: 'flex', gap: 10, marginTop: 10 }}>
              <Btn variant="ghost" onClick={() => setStep(2)}>← Back</Btn>
              <Btn full onClick={submit}>Submit feedback</Btn>
            </div>
          </Fade>
        )}
      </Card>

      <div style={{ textAlign: 'center', marginTop: 20 }}>
        <button onClick={onAdmin} style={{ fontFamily: T.font.body, fontSize: 12.5, color: T.color.textFaint, background: 'none', border: 'none', cursor: 'pointer', textDecoration: 'underline', textUnderlineOffset: 3 }}>Admin Dashboard</button>
      </div>
    </div>
  );
}

Object.assign(window, { FeedbackPortal });
