/* ============================================================
   Lectual — Funnel views: Assessment, Computing, Results, Booking
   Reuses window.{Gauge,I,Echo,applyTheme,THEMES,bandColor,useToasts}
   ============================================================ */
const QS = window.FUNNEL_QUESTIONS;
const ROADMAP = window.FUNNEL_ROADMAP;
const SKIP = window.FUNNEL_SKIP;
const DAYS = window.FUNNEL_DAYS;
const FATTY = window.FUNNEL_ATTORNEY;

const xsv = (p, sw = 2) => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={sw} strokeLinecap="round" strokeLinejoin="round">{p}</svg>;
const XI = {
  shield: xsv(<><path d="M12 3l8 3v6c0 5-3.5 8-8 9-4.5-1-8-4-8-9V6z" /><path d="M9 12l2 2 4-4" /></>),
  lock:   xsv(<><rect x="4" y="10" width="16" height="11" rx="2" /><path d="M8 10V7a4 4 0 0 1 8 0v3" /></>),
  dollar: xsv(<><path d="M12 3v18M16 7H10a3 3 0 0 0 0 6h4a3 3 0 0 1 0 6H8" /></>),
  cal:    xsv(<><rect x="3" y="5" width="18" height="16" rx="2" /><path d="M3 9h18M8 3v4M16 3v4" /></>),
  video:  xsv(<><rect x="3" y="6" width="13" height="12" rx="2" /><path d="M16 10l5-3v10l-5-3z" /></>),
  clock:  xsv(<><circle cx="12" cy="12" r="9" /><path d="M12 8v4l3 2" /></>),
  bolt:   xsv(<><path d="M13 2L4 14h7l-1 8 9-12h-7z" /></>),
  map:    xsv(<><path d="M9 5l6-2 6 2v14l-6-2-6 2-6-2V3z" /><path d="M9 5v14M15 3v14" /></>),
  star:   xsv(<><path d="M12 3l2.6 6.3L21 10l-5 4.3L17.5 21 12 17.3 6.5 21 8 14.3 3 10l6.4-.7z" /></>),
};

/* ---- scoring ---- */
function computeResult(a) {
  const protect = a.protect || [];
  let s = 58;
  if (a.conflict === 'coined') s += 14; else if (a.conflict === 'seen') s -= 12; else if (a.conflict === 'unsure') s -= 2;
  if (a.inuse === 'selling') s += 12; else if (a.inuse === 'soon') s += 4; else if (a.inuse === 'idea') s -= 8;
  if (a.urgency === 'launch' || a.urgency === 'raise') s += 6;
  if (a.budget === 'high') s += 6; else if (a.budget === 'mid') s += 3;
  if (protect.length >= 2) s += 3;
  s = Math.max(28, Math.min(95, s));

  const road = [];
  if (a.conflict !== 'coined') road.push('clearance');
  if (protect.includes('name')) road.push('wordmark');
  else if (protect.includes('logo')) road.push('wordmark');
  if (protect.includes('logo')) road.push('logo');
  if (protect.includes('work')) road.push('copyright');
  if (road.length === 0) road.push('clearance', 'wordmark');

  const flags = [];
  if (a.conflict === 'seen') flags.push({ sev: 'high', t: <><b>A similar name may already exist.</b> Worth a quick clearance search before you invest in filing.</> });
  else if (a.conflict === 'unsure') flags.push({ sev: 'med', t: <><b>Your name hasn’t been cleared yet.</b> A search confirms it’s free to register.</> });
  if (a.inuse === 'idea') flags.push({ sev: 'med', t: <><b>You’re not in market yet.</b> You can still file now as “intent to use” to claim your spot.</> });
  if (protect.includes('invention')) flags.push({ sev: 'med', t: <><b>You mentioned an invention.</b> Patents are a separate track — we’ll connect you with the right counsel.</> });
  if (flags.length === 0) flags.push({ sev: 'med', t: <><b>One small thing:</b> confirm your goods &amp; services description before filing to avoid a delay.</> });

  const skip = [];
  if (!protect.includes('invention')) skip.push(SKIP.patent);
  skip.push(SKIP.intl);
  if (protect.includes('name')) skip.push(SKIP.trademark_each);

  const ipType = protect.includes('work') && !protect.includes('name') && !protect.includes('logo') ? 'Copyright' : protect.includes('work') ? 'Trademark + Copyright' : 'Trademark';
  const urgency = a.urgency === 'launch' ? { t: 'Time-sensitive', hot: true } : a.urgency === 'raise' ? { t: 'Investor-driven', hot: true } : { t: 'No immediate deadline', hot: false };

  return { score: s, road: road.slice(0, 4), flags: flags.slice(0, 3), skip: skip.slice(0, 3), ipType, urgency };
}
window.computeResult = computeResult;

/* ============================ INTRO ============================ */
function Intro({ onStart }) {
  return (
    <div className="stage-card fintro">
      <div className="badge">{XI.lock} Private &amp; secure</div>
      <h1>Is your idea protected?</h1>
      <p>Answer a few plain-English questions and get a clear readiness score, a prioritized roadmap, and the right next step — in about two minutes.</p>
      <div className="meta">
        <div className="m">{XI.clock} ~2 minutes</div>
        <div className="m">{XI.shield} No legalese</div>
        <div className="m">{XI.lock} We never train on your idea</div>
      </div>
      <button className="btn btn-primary btn-lg" onClick={onStart}>Check my readiness {I.arrow}</button>
    </div>
  );
}

/* ============================ ASSESSMENT ============================ */
function Assessment({ idx, q, answers, setAnswer, onNext, onBack }) {
  const val = answers[q.id];
  const answered = q.kind === 'multi' ? (val && val.length > 0) : !!val;
  const toggle = (v) => {
    if (q.kind === 'multi') {
      const cur = val || [];
      setAnswer(q.id, cur.includes(v) ? cur.filter((x) => x !== v) : [...cur, v]);
    } else {
      setAnswer(q.id, v);
    }
  };
  const pct = Math.round(((idx) / QS.length) * 100);
  return (
    <div className="stage-card">
      <div className="fprog"><div className="bar"><i style={{ width: pct + '%' }} /></div><span className="lbl">{idx + 1} / {QS.length}</span></div>
      <div className="qhead">
        <div className="qn">Question {idx + 1}</div>
        <h2>{q.q}</h2>
        {q.help && <div className="help">{q.help}</div>}
      </div>
      <div className="opts">
        {q.options.map((o) => {
          const sel = q.kind === 'multi' ? (val || []).includes(o.v) : val === o.v;
          return (
            <button key={o.v} className={'opt ' + q.kind + (sel ? ' sel' : '')} onClick={() => toggle(o.v)}>
              <span className="box">{I.check}</span>
              <span>{o.label}</span>
              {o.tag && <span className="tag">{o.tag}</span>}
            </button>
          );
        })}
      </div>
      <div className="fnav">
        {idx > 0 && <button className="back" onClick={onBack}>← Back</button>}
        <span className="sp" />
        <button className="btn btn-primary" disabled={!answered} style={{ opacity: answered ? 1 : .5 }} onClick={onNext}>
          {idx === QS.length - 1 ? 'See my results' : 'Continue'} {I.arrow}
        </button>
      </div>
    </div>
  );
}

/* ============================ COMPUTING ============================ */
function Computing({ onDone }) {
  const phrases = ['Reading your answers…', 'Checking name distinctiveness…', 'Scanning for conflicts…', 'Building your roadmap…'];
  const [p, setP] = useState(0);
  useEffect(() => {
    const iv = setInterval(() => setP((x) => Math.min(phrases.length - 1, x + 1)), 560);
    const to = setTimeout(onDone, 2300);
    return () => { clearInterval(iv); clearTimeout(to); };
  }, []);
  return (
    <div className="stage-card computing">
      <div className="ring" />
      <div className="ph">Analyzing your IP readiness</div>
      <div className="ps">{phrases[p]}</div>
    </div>
  );
}

/* ============================ RESULTS ============================ */
function Results({ result, onBook }) {
  return (
    <div className="stage-card wide">
      <div className="res-hero">
        <div className="k">Your IP readiness</div>
        <div className="res-gauge"><Gauge value={result.score} size={150} stroke={14} /></div>
        <h1>{result.score >= 80 ? 'You’re in strong shape.' : result.score >= 55 ? 'You’re close — a few steps to go.' : 'Let’s strengthen your position.'}</h1>
        <p>{result.score >= 80
          ? 'Your name looks distinctive and protectable. A focused filing locks it down.'
          : result.score >= 55
          ? 'You’ve got real foundations. Clearing a couple of items gets you to a clean filing.'
          : 'There’s work to do before filing — but it’s all doable, and we’ll show you the order.'}</p>
        <div className="res-pills">
          <span className="rpill">{XI.shield} {result.ipType}</span>
          <span className={'rpill' + (result.urgency.hot ? ' hot' : '')}>{XI.clock} {result.urgency.t}</span>
          <span className="rpill">{result.flags.length} thing{result.flags.length !== 1 ? 's' : ''} to watch</span>
        </div>
      </div>

      <div className="res-sec">
        <div className="sh"><span style={{ color: 'var(--warning)' }}>{I.flag}</span><span className="t">Worth your attention</span><span className="ct">max 3</span></div>
        <div className="flags">
          {result.flags.map((f, i) => (
            <div className={'rflag ' + f.sev} key={i}><span className="fi" style={{ display: 'grid', placeItems: 'center' }}>{I.flag}</span><span className="ft">{f.t}</span></div>
          ))}
        </div>
      </div>

      <div className="res-sec">
        <div className="sh"><span style={{ color: 'var(--firm-primary)' }}>{XI.map}</span><span className="t">Your roadmap</span></div>
        <div className="roadmap">
          {result.road.map((id, i) => {
            const r = ROADMAP[id];
            return (
              <div className="rmstep" key={id}>
                <span className="num">{i + 1}</span>
                <div>
                  <div className="rt">{r.title} <span className="rtag">{r.tag}</span></div>
                  <div className="rw">{r.why}</div>
                </div>
                <div className="cost">{r.cost}<span>est. all-in</span></div>
              </div>
            );
          })}
        </div>
      </div>

      <div className="skip">
        <div className="sh">{XI.shield}<span className="t">What you do <em>not</em> need</span></div>
        {result.skip.map((s, i) => (
          <div className="si" key={i}>{I.check}<span><b>{s.t}.</b> {s.d}</span></div>
        ))}
      </div>

      <div className="res-cta">
        <div className="av">{FATTY.initials}</div>
        <h3>Talk it through with {FATTY.name.split(' ')[0]}</h3>
        <p>{FATTY.name}, {FATTY.title}. We matched you for your IP type — book a free 20-minute call to turn this roadmap into action.</p>
        <button className="btn btn-primary btn-lg" onClick={onBook}>Book my free call {I.arrow}</button>
        <div className="rate">★ {FATTY.rating} · {FATTY.reviews} reviews · {FATTY.firm}</div>
      </div>
    </div>
  );
}

/* ============================ BOOKING ============================ */
function Booking({ onBack, pushToast }) {
  const [step, setStep] = useState(0);
  const [contact, setContact] = useState({ name: '', email: '', brand: '' });
  const [day, setDay] = useState(1);
  const [slot, setSlot] = useState(null);
  const dd = DAYS[day];

  const icsHref = useMemo(() => {
    const body = `BEGIN:VCALENDAR\nVERSION:2.0\nBEGIN:VEVENT\nSUMMARY:Lectual — IP discovery call with ${FATTY.name}\nDESCRIPTION:Free 20-minute consultation\nEND:VEVENT\nEND:VCALENDAR`;
    return 'data:text/calendar;charset=utf-8,' + encodeURIComponent(body);
  }, []);

  if (step === 2) {
    return (
      <div className="stage-card confirm">
        <div className="seal">{I.check}</div>
        <h1>You’re booked.</h1>
        <p>A calendar invite and Zoom link are on their way to {contact.email || 'your inbox'}. Dana will have your readiness report ready.</p>
        <div className="confirm-card">
          <div className="crow2"><span className="ci">{XI.cal}</span><div><div className="ck">WHEN</div><div className="cvv">{dd.d}, {dd.date} · {slot}</div></div></div>
          <div className="crow2"><span className="ci">{XI.video}</span><div><div className="ck">WHERE</div><div className="cvv">Zoom · link in your invite</div></div></div>
          <div className="crow2"><span className="ci">{XI.shield}</span><div><div className="ck">WITH</div><div className="cvv">{FATTY.name} · {FATTY.firm}</div></div></div>
        </div>
        <ul className="expect">
          <div className="t">What to expect</div>
          <li>{I.check}A plain-English walk-through of your readiness report.</li>
          <li>{I.check}Honest answers — including if you don’t need to file yet.</li>
          <li>{I.check}A clear quote and next steps. No pressure, no jargon.</li>
        </ul>
        <div style={{ display: 'flex', gap: 10, marginTop: 18 }}>
          <a className="btn btn-secondary btn-block" href={icsHref} download="lectual-call.ics">Add to calendar</a>
        </div>
      </div>
    );
  }

  return (
    <div className="stage-card">
      <div className="book-steps">
        <div className={'bs ' + (step > 0 ? 'done' : 'cur')}><span className="bdot">{step > 0 ? I.check : '1'}</span></div>
        <span className={'bl' + (step > 0 ? ' done' : '')} />
        <div className={'bs ' + (step === 1 ? 'cur' : '')}><span className="bdot">2</span></div>
      </div>

      {step === 0 ? (
        <React.Fragment>
          <div className="qhead"><div className="qn">Step 1 of 2</div><h2>Where should we send your invite?</h2></div>
          <div className="field"><label>Your name</label><input className="input" value={contact.name} onChange={(e) => setContact({ ...contact, name: e.target.value })} placeholder="Maya Okonkwo" /></div>
          <div className="field"><label>Work email</label><input className="input" type="email" value={contact.email} onChange={(e) => setContact({ ...contact, email: e.target.value })} placeholder="maya@pathset.co" /></div>
          <div className="field"><label>Brand or company</label><input className="input" value={contact.brand} onChange={(e) => setContact({ ...contact, brand: e.target.value })} placeholder="Pathset" /></div>
          <div className="fnav"><button className="back" onClick={onBack}>← Back to results</button><span className="sp" /><button className="btn btn-primary" onClick={() => setStep(1)}>Pick a time {I.arrow}</button></div>
        </React.Fragment>
      ) : (
        <React.Fragment>
          <div className="qhead"><div className="qn">Step 2 of 2</div><h2>Pick a time that works</h2><div className="help">Free · 20 minutes · over Zoom</div></div>
          <div className="daypick">
            {DAYS.map((d, i) => (
              <div key={d.date} className={'day' + (day === i ? ' sel' : '')} onClick={() => { setDay(i); setSlot(null); }}>
                <div className="dn">{d.d}</div><div className="dd">{d.date.split(' ')[1]}</div><div className="dc">{d.slots.length} open</div>
              </div>
            ))}
          </div>
          <div className="slots">
            {dd.slots.map((s) => <div key={s} className={'slot' + (slot === s ? ' sel' : '')} onClick={() => setSlot(s)}>{s}</div>)}
          </div>
          <div className="fnav"><button className="back" onClick={() => setStep(0)}>← Back</button><span className="sp" /><button className="btn btn-primary" disabled={!slot} style={{ opacity: slot ? 1 : .5 }} onClick={() => setStep(2)}>Confirm booking {I.arrow}</button></div>
        </React.Fragment>
      )}
    </div>
  );
}

Object.assign(window, { XI, Intro, Assessment, Computing, Results, Booking });
