/* survey.jsx — Sections 10 + 11 (Mini survey & Thank You) */

const svStyles = `
  .survey-wrap {
    margin-top: 44px;
    background: var(--ink);
    color: var(--cream);
    border-radius: 28px;
    padding: clamp(36px, 5vw, 56px);
    position: relative;
    overflow: hidden;
  }
  .survey-wrap::before {
    content: ""; position: absolute; inset: 0;
    background:
      radial-gradient(60% 40% at 100% 0%, color-mix(in oklab, var(--terracotta) 60%, transparent) 0%, transparent 60%),
      radial-gradient(40% 30% at 0% 100%, color-mix(in oklab, var(--moss) 40%, transparent) 0%, transparent 60%);
    opacity: 0.5; pointer-events: none;
  }
  .survey-wrap > * { position: relative; z-index: 1; }
  .survey-head { display: flex; align-items: flex-end; justify-content: space-between; gap: 24px; flex-wrap: wrap; margin-bottom: 28px; }
  .survey-head h3 { color: var(--cream); font-size: clamp(28px, 3vw, 38px); line-height: 1.15; max-width: 540px; }
  .survey-head p { color: color-mix(in oklab, var(--cream) 75%, transparent); font-size: 15px; max-width: 460px; }
  .survey-progress {
    display: flex; gap: 6px; margin: 4px 0 24px;
  }
  .survey-progress i {
    flex: 1; height: 4px; border-radius: 999px;
    background: rgba(255,255,255,0.12);
    transition: background .25s ease;
  }
  .survey-progress i.done { background: var(--terracotta); }
  .survey-progress i.current { background: var(--terracotta-soft); }

  .survey-stage {
    min-height: 360px;
    background: rgba(255,255,255,0.04);
    border: 1px solid rgba(255,255,255,0.08);
    border-radius: 20px;
    padding: 32px;
    position: relative;
  }
  .q-step { display: flex; flex-direction: column; gap: 16px; }
  .q-label { font-size: 13px; letter-spacing: 0.1em; text-transform: uppercase; color: var(--terracotta-soft); font-weight: 500; }
  .q-prompt { font-family: var(--font-head); font-size: clamp(22px, 2.2vw, 28px); line-height: 1.25; font-weight: 400; color: var(--cream); }
  .q-help { color: color-mix(in oklab, var(--cream) 65%, transparent); font-size: 14px; line-height: 1.5; }
  .q-examples { display: flex; flex-direction: column; gap: 8px; margin-top: 8px; }
  .q-examples small { color: color-mix(in oklab, var(--cream) 55%, transparent); font-size: 12.5px; letter-spacing: 0.06em; text-transform: uppercase; font-weight: 500; }
  .q-examples .ex {
    padding: 10px 14px; border-radius: 12px;
    background: rgba(255,255,255,0.04); border: 1px solid rgba(255,255,255,0.08);
    color: color-mix(in oklab, var(--cream) 80%, transparent);
    font-style: italic; font-size: 14px;
    cursor: pointer; transition: background .2s ease, transform .15s ease;
  }
  .q-examples .ex:hover { background: rgba(255,255,255,0.08); transform: translateX(2px); }

  .ta-wrap { position: relative; }
  .ta-wrap textarea {
    width: 100%; resize: vertical; min-height: 100px;
    background: rgba(255,255,255,0.06);
    border: 1px solid rgba(255,255,255,0.16);
    border-radius: 14px;
    color: var(--cream);
    padding: 14px 16px;
    font: 400 16px/1.5 var(--font-body);
    transition: border-color .2s ease, background .2s ease;
  }
  .ta-wrap textarea::placeholder { color: color-mix(in oklab, var(--cream) 40%, transparent); }
  .ta-wrap textarea:focus {
    outline: none; border-color: var(--terracotta);
    background: rgba(255,255,255,0.1);
  }
  .ta-count {
    position: absolute; bottom: 8px; right: 12px;
    font-size: 11px; color: color-mix(in oklab, var(--cream) 50%, transparent);
    font-variant-numeric: tabular-nums;
  }

  .choice-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-top: 6px; }
  @media (max-width: 600px) { .choice-grid { grid-template-columns: 1fr; } }
  .choice {
    display: flex; align-items: center; gap: 12px;
    padding: 12px 16px;
    background: rgba(255,255,255,0.04);
    border: 1px solid rgba(255,255,255,0.12);
    border-radius: 12px;
    color: var(--cream);
    cursor: pointer; text-align: left; font-size: 14.5px;
    transition: background .2s ease, border-color .2s ease;
  }
  .choice:hover { background: rgba(255,255,255,0.09); border-color: rgba(255,255,255,0.22); }
  .choice .box {
    width: 18px; height: 18px; border-radius: 5px;
    border: 1.5px solid rgba(255,255,255,0.4);
    flex-shrink: 0; display: grid; place-items: center;
    transition: background .2s ease, border-color .2s ease;
  }
  .choice.round .box { border-radius: 50%; }
  .choice.picked .box {
    background: var(--terracotta); border-color: var(--terracotta);
  }
  .choice.picked .box svg { color: #fff; }
  .choice.picked { border-color: var(--terracotta); background: color-mix(in oklab, var(--terracotta) 16%, transparent); }
  .choice .box svg { width: 12px; height: 12px; color: transparent; }

  .email-row { display: flex; gap: 10px; flex-wrap: wrap; align-items: center; }
  .email-row input {
    flex: 1; min-width: 240px;
    background: rgba(255,255,255,0.06);
    border: 1px solid rgba(255,255,255,0.16);
    border-radius: 14px;
    color: var(--cream);
    padding: 14px 16px;
    font: 400 16px/1.4 var(--font-body);
  }
  .email-row input::placeholder { color: color-mix(in oklab, var(--cream) 40%, transparent); }
  .email-row input:focus { outline: none; border-color: var(--terracotta); background: rgba(255,255,255,0.1); }

  .survey-nav { display: flex; justify-content: space-between; align-items: center; margin-top: 22px; gap: 12px; flex-wrap: wrap; }
  .survey-nav .crumb { font-size: 13px; color: color-mix(in oklab, var(--cream) 60%, transparent); font-variant-numeric: tabular-nums; }
  .btn.ink-ghost { background: transparent; color: var(--cream); border: 1px solid rgba(255,255,255,0.22); }
  .btn.ink-ghost:hover { background: rgba(255,255,255,0.06); }

  /* Thank you state */
  .thank-stage {
    min-height: 360px;
    display: flex; flex-direction: column; gap: 22px;
    padding: 16px 4px;
  }
  .thank-rank {
    font-family: var(--font-head);
    font-size: clamp(56px, 8vw, 96px);
    line-height: 1; color: var(--terracotta-soft); letter-spacing: -0.03em;
    font-weight: 300;
  }
  .thank-rank b { color: var(--cream); font-weight: 400; font-style: italic; }
  .thank-row {
    display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 12px;
  }
  @media (max-width: 720px) { .thank-row { grid-template-columns: 1fr; } }
  .thank-tile {
    background: rgba(255,255,255,0.04);
    border: 1px solid rgba(255,255,255,0.1);
    border-radius: 14px;
    padding: 14px 16px;
    color: var(--cream);
    font-size: 14px;
    display: flex; align-items: center; gap: 10px;
  }
  .thank-tile .icon { width: 28px; height: 28px; border-radius: 8px; background: color-mix(in oklab, var(--terracotta) 24%, transparent); color: var(--terracotta-soft); display: grid; place-items: center; flex-shrink: 0; }

  .ref-link {
    display: flex; align-items: center; gap: 8px;
    background: rgba(255,255,255,0.06);
    border: 1px solid rgba(255,255,255,0.16);
    border-radius: 12px;
    padding: 10px 14px;
    font-family: var(--font-mono);
    font-size: 13px;
    color: color-mix(in oklab, var(--cream) 80%, transparent);
  }
  .ref-link input {
    flex: 1; background: transparent; border: 0; color: inherit; font: inherit;
    outline: none;
  }
  .share-row { display: flex; gap: 10px; flex-wrap: wrap; }
  .share-row .btn { font-size: 13px; padding: 9px 14px; }

  .founder-call {
    margin-top: 14px;
    padding: 18px 20px;
    border: 1px dashed color-mix(in oklab, var(--terracotta) 55%, transparent);
    border-radius: 14px;
    color: var(--cream);
    background: color-mix(in oklab, var(--terracotta) 12%, transparent);
    display: flex; align-items: center; gap: 16px; justify-content: space-between; flex-wrap: wrap;
  }
  .founder-call .lead { font-size: 14.5px; line-height: 1.4; max-width: 540px; }
  .founder-call .lead b { color: var(--terracotta-soft); font-weight: 600; }

  /* Family caregiver modal */
  .modal-back {
    position: fixed; inset: 0; z-index: 100;
    background: color-mix(in oklab, var(--ink) 60%, transparent);
    backdrop-filter: blur(8px);
    display: grid; place-items: center;
    padding: 20px;
    animation: fadeIn .25s ease;
  }
  @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
  .modal {
    width: 100%; max-width: 560px;
    background: var(--paper);
    border-radius: 22px;
    padding: 36px 32px 30px;
    position: relative;
    box-shadow: 0 40px 80px -30px rgba(0,0,0,0.4);
    border: 1px solid var(--line);
  }
  .modal .x {
    position: absolute; top: 16px; right: 16px;
    width: 32px; height: 32px;
    background: transparent;
    border: 1px solid var(--line);
    border-radius: 50%;
    cursor: pointer; color: var(--ink-soft);
    display: grid; place-items: center;
  }
  .modal h3 { font-size: 28px; line-height: 1.15; }
  .modal p { color: var(--ink-soft); font-size: 15px; line-height: 1.55; margin-top: 10px; }
  .modal ul { padding-left: 20px; margin-top: 14px; color: var(--ink-soft); font-size: 14.5px; line-height: 1.7; }
  .modal ul li b { color: var(--ink); font-weight: 500; }
`;

const Q1_EXAMPLES = [
  '"When my dog is on the couch even though they\'re not allowed"',
  '"When my mom is in the kitchen at 3am again"',
  '"When a delivery is left at the door but no one picks it up"',
  '"When the kids come home from school"',
];

const Q2_OPTIONS = [
  { v: 'caregiver', label: 'Live with aging parent or family member I worry about' },
  { v: 'solo',      label: 'Live alone, want to feel safer' },
  { v: 'pet',       label: 'Have pets at home while I\'m out' },
  { v: 'parent',    label: 'Have young kids' },
  { v: 'other',     label: 'Other' },
];

const Q3_OPTIONS = ['Ring', 'Nest', 'Arlo', 'Eufy', 'Wyze', 'Tapo', 'Old phone', 'None', 'Other'];

const Q4_OPTIONS = [
  { v: 'daily', label: 'Multiple times a day' },
  { v: 'weekly', label: 'A few times a week' },
  { v: 'sometimes', label: 'Occasionally' },
  { v: 'rarely', label: 'Rarely' },
  { v: 'off', label: 'I turned off notifications' },
];

const Q5_OPTIONS = [
  { v: '5',   label: 'Yes, $5/month' },
  { v: '10',  label: 'Yes, $10/month' },
  { v: '20',  label: 'Yes, $20/month' },
  { v: 'ads', label: 'Free with ads' },
  { v: 'no',  label: 'No' },
];

function Choice({ active, multi, onClick, children }) {
  return (
    <button type="button" className={`choice ${multi ? '' : 'round'} ${active ? 'picked' : ''}`} onClick={onClick}>
      <span className="box">
        <svg viewBox="0 0 12 12" fill="none"><path d="M2 6l3 3 5-6" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
      </span>
      <span>{children}</span>
    </button>
  );
}

function SurveySection({ productName, prefill, onPrefillConsumed }) {
  const [step, setStep] = React.useState(0);
  const [a1, setA1] = React.useState('');
  const [a2, setA2] = React.useState('');
  const [a3, setA3] = React.useState([]);
  const [a4, setA4] = React.useState('');
  const [a5, setA5] = React.useState('');
  const [email, setEmail] = React.useState('');
  const [submitted, setSubmitted] = React.useState(false);
  const [rank] = React.useState(() => 412 + Math.floor(Math.random() * 16));
  const refLink = `${productName.toLowerCase()}.house/r/${(rank * 7).toString(36)}`;

  // Apply prefill (use case + tier)
  React.useEffect(() => {
    if (!prefill) return;
    if (prefill.useCase) {
      const mapping = { A: 'caregiver', B: 'pet', C: 'solo', D: 'parent', E: 'solo' };
      setA2((cur) => cur || mapping[prefill.useCase] || cur);
      const seed = {
        A: 'When grandma stays in the bathroom longer than usual',
        B: 'When the dog has an accident while I\'m out',
        C: 'When someone I don\'t know approaches the garage between 5-7pm',
        D: 'When the baby is crying for more than 2 minutes and no one\'s gone to them',
        E: 'When the smoke alarm goes off or glass breaks while I\'m out',
      };
      if (seed[prefill.useCase] && !a1) setA1(seed[prefill.useCase]);
    }
    if (prefill.tier && !a5) {
      setA5(prefill.tier === 'plus' ? '10' : prefill.tier === 'pro' ? '20' : '5');
    }
    onPrefillConsumed && onPrefillConsumed();
  }, [prefill]);

  const TOTAL = 5;
  const canNext = [a1.trim().length >= 4, !!a2, a3.length > 0, !!a4, !!a5][step];
  const isLast = step === TOTAL - 1;

  const submit = () => {
    if (!email.match(/^[^\s@]+@[^\s@]+\.[^\s@]+$/)) return;
    setSubmitted(true);
    const lead = { email: email, alertWish: a1, persona: a2, cameras: a3, alertFrequency: a4, wouldPay: a5, rank: rank };
    try { localStorage.setItem('care_lead', JSON.stringify({ ...lead, ts: Date.now() })); } catch (e) {}
    try {
      if (window.db) {
        window.db.collection('leads').add({ ...lead, createdAt: firebase.firestore.FieldValue.serverTimestamp() }).catch(function () {});
      }
    } catch (e) {}
  };

  const copy = () => {
    try { navigator.clipboard.writeText(refLink); } catch (e) {}
  };

  return (
    <section id="survey" data-screen-label="10 Survey">
      <div className="wrap">
        <SectionHead
          eyebrow="Tell us what your camera misses"
          title={<>Five questions.<br /><span style={{ fontStyle: 'italic', color: 'var(--terracotta-deep)' }}>Your answers shape what we build.</span></>}
          lead="Help us build the alerts you wish you had. We'll send you early access, and 50% off the first year for being early."
        />
        <div className="survey-wrap">
          {!submitted ? (
            <>
              <div className="survey-head">
                <div>
                  <h3>Five quick questions.</h3>
                  <div className="survey-progress" aria-hidden>
                    {Array.from({ length: TOTAL }).map((_, i) => (
                      <i key={i} className={i < step ? 'done' : i === step ? 'current' : ''} />
                    ))}
                  </div>
                </div>
                <p>This goes straight to Elena.<br />Free-text answers shape the product roadmap more than any feature spec.</p>
              </div>

              <div className="survey-stage">
                {step === 0 && (
                  <div className="q-step">
                    <span className="q-label">Question 1 of 5 · the goldmine</span>
                    <div className="q-prompt">What's the alert you wish your camera would notice, but doesn't?</div>
                    <div className="q-help">Be specific. The more concrete, the better. Examples of what others have told us:</div>
                    <div className="q-examples">
                      {Q1_EXAMPLES.map((ex, i) => (
                        <button key={i} type="button" className="ex" onClick={() => setA1(ex.replace(/^"|"$/g, ''))}>
                          {ex}
                        </button>
                      ))}
                    </div>
                    <div className="ta-wrap" style={{ marginTop: 8 }}>
                      <textarea
                        value={a1}
                        maxLength={300}
                        onChange={(e) => setA1(e.target.value)}
                        placeholder="Now you. Write the one your current camera keeps missing."
                      />
                      <div className="ta-count">{a1.length}/300</div>
                    </div>
                  </div>
                )}
                {step === 1 && (
                  <div className="q-step">
                    <span className="q-label">Question 2 of 5 · who is this for?</span>
                    <div className="q-prompt">Which one sounds most like you?</div>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 6 }}>
                      {Q2_OPTIONS.map((o) => (
                        <Choice key={o.v} active={a2 === o.v} onClick={() => setA2(o.v)}>{o.label}</Choice>
                      ))}
                    </div>
                  </div>
                )}
                {step === 2 && (
                  <div className="q-step">
                    <span className="q-label">Question 3 of 5 · what you've tried</span>
                    <div className="q-prompt">What cameras do you have right now?</div>
                    <div className="q-help">Pick any that apply.</div>
                    <div className="choice-grid">
                      {Q3_OPTIONS.map((o) => (
                        <Choice key={o} multi active={a3.includes(o)} onClick={() => setA3((cur) => cur.includes(o) ? cur.filter((x) => x !== o) : [...cur, o])}>{o}</Choice>
                      ))}
                    </div>
                  </div>
                )}
                {step === 3 && (
                  <div className="q-step">
                    <span className="q-label">Question 4 of 5 · the false-alarm tax</span>
                    <div className="q-prompt">How often does your camera cry wolf?</div>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 6 }}>
                      {Q4_OPTIONS.map((o) => (
                        <Choice key={o.v} active={a4 === o.v} onClick={() => setA4(o.v)}>{o.label}</Choice>
                      ))}
                    </div>
                  </div>
                )}
                {step === 4 && (
                  <div className="q-step">
                    <span className="q-label">Question 5 of 5 · what's it worth</span>
                    <div className="q-prompt">If {productName} actually got this right, what would you pay?</div>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 6 }}>
                      {Q5_OPTIONS.map((o) => (
                        <Choice key={o.v} active={a5 === o.v} onClick={() => setA5(o.v)}>{o.label}</Choice>
                      ))}
                    </div>
                    <div style={{ marginTop: 16 }}>
                      <span className="q-label">Email for beta access</span>
                      <div className="email-row" style={{ marginTop: 8 }}>
                        <input type="email" placeholder="you@example.com" value={email} onChange={(e) => setEmail(e.target.value)} />
                        <button className="btn accent" onClick={submit} disabled={!email.match(/^[^\s@]+@[^\s@]+\.[^\s@]+$/)} style={{ opacity: email.match(/^[^\s@]+@[^\s@]+\.[^\s@]+$/) ? 1 : 0.55 }}>
                          Request beta access
                          <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M3 7h8M7 3l4 4-4 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
                        </button>
                      </div>
                    </div>
                  </div>
                )}
              </div>

              <div className="survey-nav">
                <span className="crumb">Step {step + 1} of {TOTAL} · ~{60 - step * 12}s left</span>
                <div style={{ display: 'flex', gap: 10 }}>
                  {step > 0 && <button className="btn ink-ghost sm" onClick={() => setStep(step - 1)}>Back</button>}
                  {!isLast && (
                    <button className="btn accent sm" onClick={() => setStep(step + 1)} disabled={!canNext} style={{ opacity: canNext ? 1 : 0.5 }}>
                      Continue
                      <svg width="13" height="13" viewBox="0 0 13 13" fill="none"><path d="M3 6.5h7M6.5 3l3.5 3.5L6.5 10" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
                    </button>
                  )}
                </div>
              </div>
            </>
          ) : (
            <div data-screen-label="11 Thank you">
              <div className="survey-head" style={{ marginBottom: 8 }}>
                <div>
                  <span className="q-label">You're in</span>
                  <div className="thank-rank">#<b>{rank}</b></div>
                </div>
                <p style={{ maxWidth: 380 }}>Confirmation just hit your inbox. We'll be in touch when early access opens in Q3 2026.</p>
              </div>

              <div className="thank-row">
                <div className="thank-tile">
                  <span className="icon"><svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M1 3h12v8H1z" stroke="currentColor" strokeWidth="1.4"/><path d="M1 3l6 5 6-5" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round"/></svg></span>
                  Confirmation email sent
                </div>
                <div className="thank-tile">
                  <span className="icon"><svg width="14" height="14" viewBox="0 0 14 14" fill="none"><rect x="2" y="3" width="10" height="10" rx="2" stroke="currentColor" strokeWidth="1.4"/><path d="M2 6h10M6 1v3" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/></svg></span>
                  You'll be notified Q3 2026
                </div>
                <div className="thank-tile">
                  <span className="icon"><svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M7 1l1.7 3.6L12.5 5l-3 2.9.7 4.1L7 10l-3.2 2 .7-4.1-3-2.9 3.8-.4z" stroke="currentColor" strokeWidth="1.3" strokeLinejoin="round"/></svg></span>
                  50% off {productName}+ for year one
                </div>
              </div>

              <div className="q-help" style={{ marginTop: 20, color: 'color-mix(in oklab, var(--cream) 75%, transparent)', fontSize: 15 }}>
                Know someone else watching over a parent, a young kid, or a pet at home? Here's a link you can send them.
              </div>
              <div className="ref-link">
                <span style={{ color: 'var(--terracotta-soft)' }}>↗</span>
                <input readOnly value={refLink} onClick={(e) => e.target.select()} />
                <button className="btn ink-ghost sm" onClick={copy} style={{ padding: '7px 12px', fontSize: 12 }}>Copy</button>
              </div>
            </div>
          )}
        </div>
      </div>
      <style dangerouslySetInnerHTML={{ __html: svStyles }} />
    </section>
  );
}

function FamilyModal({ onClose, productName }) {
  return (
    <div className="modal-back" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <button className="x" onClick={onClose} aria-label="Close">
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M3 3l8 8M11 3l-8 8" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/></svg>
        </button>
        <div className="eyebrow">For family caregivers</div>
        <h3 style={{ marginTop: 10 }}>Watching over a family member from afar?</h3>
        <p>
          You're not the user. They are. That changes everything about how a camera should work.
        </p>
        <p style={{ marginTop: 14, color: 'var(--ink)', fontWeight: 500 }}>{productName} for Family is designed for:</p>
        <ul>
          <li><b>The adult child</b> watching mom from another city</li>
          <li><b>The spouse</b> traveling for work</li>
          <li><b>The sibling</b> coordinating care across multiple family members</li>
        </ul>
        <p>Privacy-first. Dignity-preserving. Smart enough to know when to alert all of you, and when to handle it quietly.</p>
        <div style={{ display: 'flex', gap: 10, marginTop: 18, flexWrap: 'wrap' }}>
          <a href="#survey" className="btn accent" onClick={onClose}>
            Request beta access
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M3 7h8M7 3l4 4-4 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
          </a>
          <button className="btn ghost" onClick={onClose}>Maybe later</button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { SurveySection, FamilyModal });
