/* ============================================================
   Lectual — Founder views: Dashboard, Portfolio, Vault, Coach
   Reuses window.{Echo,Gauge,I,applyTheme,bandColor,useToasts} from crm/shared.jsx
   ============================================================ */
const F = window.FOUNDER;
const JOURNEY = window.FOUNDER_JOURNEY;
const PORTFOLIO = window.FOUNDER_PORTFOLIO;
const VAULT = window.FOUNDER_VAULT;
const ATTORNEY = window.FOUNDER_ATTORNEY;
const PROMPTS = window.FOUNDER_PROMPTS;
const COACH_REPLIES = window.FOUNDER_COACH_REPLIES;
const fUSD = (n) => '$' + (n >= 1000 ? (n / 1000).toFixed(n % 1000 ? 1 : 0) + 'k' : n);

/* founder-specific icons */
const fsv = (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 FI = {
  home:   fsv(<><path d="M3 11l9-8 9 8M5 10v10h14V10" /></>),
  folder: fsv(<><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" /></>),
  vault:  fsv(<><rect x="3" y="4" width="18" height="16" rx="2" /><circle cx="12" cy="12" r="3.5" /><path d="M12 4v3M12 17v3" /></>),
  chat:   fsv(<><path d="M21 12a8 8 0 0 1-11.6 7.1L4 20l1-4.2A8 8 0 1 1 21 12z" /></>),
  results:fsv(<><path d="M4 20V10M10 20V4M16 20v-7M22 20H2" /></>),
  est:    fsv(<><path d="M12 3v18M16 7H10a3 3 0 0 0 0 6h4a3 3 0 0 1 0 6H8" /></>),
  match:  fsv(<><circle cx="9" cy="9" r="3.5" /><path d="M3 20c0-3 3-5 6-5s6 2 6 5" /><path d="M16 8l2 2 4-4" /></>),
  learn:  fsv(<><path d="M3 6l9-3 9 3-9 3z" /><path d="M21 6v6M7 9v5c0 1.5 2.2 3 5 3s5-1.5 5-3V9" /></>),
  gear:   fsv(<><circle cx="12" cy="12" r="3" /><path d="M12 3v2M12 19v2M5 5l1.5 1.5M17.5 17.5L19 19M3 12h2M19 12h2M5 19l1.5-1.5M17.5 6.5L19 5" /></>),
  shield: fsv(<><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:   fsv(<><rect x="4" y="10" width="16" height="11" rx="2" /><path d="M8 10V7a4 4 0 0 1 8 0v3" /></>),
  tm:     fsv(<><circle cx="12" cy="12" r="9" /><path d="M8 9h8M12 9v7" /></>),
  cr:     fsv(<><circle cx="12" cy="12" r="9" /><path d="M15 9.5a3.5 3.5 0 1 0 0 5" /></>),
  cal:    fsv(<><rect x="3" y="5" width="18" height="16" rx="2" /><path d="M3 9h18M8 3v4M16 3v4" /></>),
  doc:    fsv(<><path d="M14 3H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z" /><path d="M14 3v6h6" /></>),
  send:   fsv(<><path d="M4 12l16-7-7 16-2.5-6.5z" /></>),
  bolt:   fsv(<><path d="M13 2L4 14h7l-1 8 9-12h-7z" /></>),
  globe:  fsv(<><circle cx="12" cy="12" r="9" /><path d="M3 12h18M12 3c3 3 3 15 0 18M12 3c-3 3-3 15 0 18" /></>),
  copy:   fsv(<><rect x="9" y="9" width="11" height="11" rx="2" /><path d="M5 15V5a2 2 0 0 1 2-2h10" /></>),
  no:     fsv(<><circle cx="12" cy="12" r="9" /><path d="M5 5l14 14" /></>),
  server: fsv(<><rect x="3" y="4" width="18" height="7" rx="2" /><rect x="3" y="13" width="18" height="7" rx="2" /><path d="M7 7.5v.01M7 16.5v.01" /></>),
};

/* ---- deterministic pseudo-QR from a seed string ---- */
function QR({ seed, modules = 23 }) {
  const cells = useMemo(() => {
    let h = 2166136261;
    for (const c of seed) { h ^= c.charCodeAt(0); h = Math.imul(h, 16777619) >>> 0; }
    const rng = () => { h = (Math.imul(h, 1664525) + 1013904223) >>> 0; return h / 4294967296; };
    const n = modules, out = [];
    const inFinder = (r, c) => {
      const box = (R, C) => r >= R && r < R + 7 && c >= C && c < C + 7;
      const sep = (R, C) => r >= R - 1 && r < R + 8 && c >= C - 1 && c < C + 8;
      return box(0, 0) || box(0, n - 7) || box(n - 7, 0) || sep(0, 0) || sep(0, n - 7) || sep(n - 7, 0);
    };
    for (let r = 0; r < n; r++) for (let c = 0; c < n; c++) {
      if (inFinder(r, c)) continue;
      if (rng() > 0.52) out.push([c, r]);
    }
    return out;
  }, [seed, modules]);

  const finder = (x, y) => (
    <g key={`f${x}${y}`}>
      <rect x={x} y={y} width="7" height="7" rx="1.4" fill="currentColor" />
      <rect x={x + 1} y={y + 1} width="5" height="5" rx="1" fill="#fff" />
      <rect x={x + 2} y={y + 2} width="3" height="3" rx=".6" fill="currentColor" />
    </g>
  );
  return (
    <svg viewBox={`0 0 ${modules} ${modules}`} style={{ color: 'var(--ink)' }} shapeRendering="crispEdges">
      {cells.map(([x, y], i) => <rect key={i} x={x + 0.08} y={y + 0.08} width="0.84" height="0.84" fill="currentColor" />)}
      {finder(0, 0)}{finder(modules - 7, 0)}{finder(0, modules - 7)}
    </svg>
  );
}

/* ============================ JOURNEY STEPPER ============================ */
function Journey() {
  return (
    <div className="journey">
      <div className="jh"><span className="t">Your protection journey</span><span className="now">Currently at <b>{JOURNEY.stages[JOURNEY.current]}</b></span></div>
      <div className="steps">
        {JOURNEY.stages.map((s, i) => {
          const cls = i < JOURNEY.current ? 'done' : i === JOURNEY.current ? 'cur' : '';
          return (
            <div className={'step ' + cls} key={s}>
              <span className="line" />
              <span className="node">{i < JOURNEY.current ? I.check : <b style={{ fontFamily: 'var(--font-mono)', fontSize: 11 }}>{i + 1}</b>}</span>
              <span className="lbl">{s}</span>
            </div>
          );
        })}
      </div>
    </div>
  );
}

/* ============================ F4 · DASHBOARD ============================ */
const FTONE = {
  plain: 'Pathset is on a strong footing.',
  warm:  'You’re doing great, Maya.',
  bold:  'Your idea is getting locked down.',
};
function Dashboard({ go, pushToast, tone = 'plain' }) {
  const protectedCount = PORTFOLIO.filter((p) => p.statusTone === 'protected').length;
  const inProgress = PORTFOLIO.filter((p) => p.statusTone === 'progress').length;
  return (
    <div className="fscroll scrollbar-thin"><div className="fwrap">
      <div className="fgrid">
        <div className="fhero">
          <div style={{ textAlign: 'center' }}>
            <Gauge value={F.score} size={132} stroke={13} />
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--protected)', fontWeight: 700, marginTop: 8 }}>Strong</div>
          </div>
          <div className="htxt">
            <div className="k">Welcome back, {F.first}</div>
            <h2>{FTONE[tone] || FTONE.plain}</h2>
            <p>Your wordmark is filed and moving through examination, your methodology is registered, and one quick clearance stands between your logo and protection. Here’s what’s next.</p>
          </div>
        </div>

        <Journey />

        <div className="frow2">
          <div className="fcard">
            <div className="ch"><span className="t">What’s next</span><button className="more" onClick={() => go('portfolio')}>Portfolio</button></div>
            <div className="nextstep">
              <span className="ni">{FI.shield}</span>
              <div style={{ flex: 1 }}><div className="nt">Finish your logo clearance</div><div className="nd">A quick search confirms your logo is free to register. Dana can run it in a day.</div></div>
              <span className="nc">~3 days</span>
            </div>
            <div className="nextstep">
              <span className="ni">{FI.cal}</span>
              <div style={{ flex: 1 }}><div className="nt">Watch for an office action</div><div className="nd">The USPTO may send questions on your wordmark. We’ll translate it and alert you.</div></div>
              <span className="nc">Aug 2026</span>
            </div>
            <div className="nextstep">
              <span className="ni">{FI.bolt}</span>
              <div style={{ flex: 1 }}><div className="nt">Consider filing your tagline</div><div className="nd">“Find your path” is distinctive enough to protect — optional, low cost.</div></div>
              <span className="nc">Optional</span>
            </div>
          </div>

          <div className="fcard">
            <div className="ch"><span className="t">Your matched attorney</span></div>
            <div className="attorney">
              <span className="av" style={{ background: ATTORNEY.color }}>{ATTORNEY.initials}</span>
              <div><div className="nm">{ATTORNEY.name}</div><div className="ti">{ATTORNEY.title}</div><div className="rt">★ {ATTORNEY.rating} · {ATTORNEY.reviews} reviews · {ATTORNEY.firm}</div></div>
            </div>
            <ul className="whylist">{ATTORNEY.why.map((w, i) => <li key={i}>{I.check}{w}</li>)}</ul>
            <div style={{ display: 'flex', gap: 10 }}>
              <button className="btn btn-primary btn-sm" onClick={() => pushToast('Opening booking…')}>Book a call {I.arrow}</button>
              <button className="btn btn-secondary btn-sm" onClick={() => go('coach')}>Ask my coach first</button>
            </div>
          </div>
        </div>

        <div className="fcard">
          <div className="ch"><span className="t">Portfolio at a glance</span><button className="more" onClick={() => go('portfolio')}>View all</button></div>
          <div className="statgrid">
            <div className="fstat"><div className="l">Assets protected</div><b style={{ color: 'var(--protected)' }}>{protectedCount}</b></div>
            <div className="fstat"><div className="l">In progress</div><b style={{ color: 'var(--firm-primary)' }}>{inProgress}</b></div>
            <div className="fstat"><div className="l">Est. portfolio value</div><b>{fUSD(F.portfolioValue)}</b></div>
          </div>
        </div>

        <div className="truststrip">
          <div className="tcell"><span className="ic">{FI.lock}</span><div><div className="h">Encrypted &amp; private</div><p>Your assets are sealed with bank-level encryption — only you control access.</p></div></div>
          <div className="tcell"><span className="ic">{FI.no}</span><div><div className="h">We never train on your ideas</div><p>Your work is never used to train AI models. Ever.</p></div></div>
          <div className="tcell"><span className="ic">{FI.shield}</span><div><div className="h">Software, not a law firm</div><p>Lectual guides you; your matched attorney gives the legal advice.</p></div></div>
        </div>
      </div>
    </div></div>
  );
}

/* ============================ F5 · IP PORTFOLIO ============================ */
function Portfolio({ go, pushToast }) {
  const stageDot = { Filed: 'var(--firm-primary)', Clearance: 'var(--warning)', Registered: 'var(--protected)', Recommended: 'var(--ink-3)' };
  return (
    <div className="fscroll scrollbar-thin"><div className="fwrap">
      <div className="pf-head">
        <div><div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '.12em', textTransform: 'uppercase', color: 'var(--ink-3)' }}>{PORTFOLIO.length} assets</div>
          <div style={{ fontSize: 14, color: 'var(--ink-2)', marginTop: 2 }}>Every mark, work, and application — with what each one needs next.</div></div>
        <div className="sumval"><div className="l">Est. total value</div><b>{fUSD(F.portfolioValue)}</b></div>
      </div>

      <div className="assetlist">
        {PORTFOLIO.map((a) => (
          <div className="asset" key={a.id} onClick={() => pushToast(`Opening ${a.name}…`)}>
            <span className={'tyi ' + (a.type === 'Copyright' ? 'cr' : 'tm')}>{a.type === 'Copyright' ? FI.cr : FI.tm}</span>
            <div>
              <div className="nm">{a.name}</div>
              <div className="sub">{a.kind} · {a.type} · {a.classes}</div>
              <div className="chips">
                <span className={'dchip ' + a.deadline.tone}>{a.deadline.tone === 'ok' ? I.check : FI.cal}{a.deadline.label} · {a.deadline.when}</span>
              </div>
            </div>
            <div className="stagewrap">
              <div className="sl">Lifecycle</div>
              <span className="stagepill" style={{ color: stageDot[a.stage] }}><span className="d" style={{ background: stageDot[a.stage] }} />{a.stage}</span>
              <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 3 }}>{a.status}</div>
            </div>
            <div className="val"><div className="l">Est. value</div><b>{fUSD(a.value)}</b></div>
          </div>
        ))}
      </div>

      <div className="fcard" style={{ marginTop: 18, display: 'flex', alignItems: 'center', gap: 16 }}>
        <span className="ni" style={{ width: 40, height: 40, borderRadius: 11, background: 'var(--accent-soft)', color: 'var(--firm-primary)', display: 'grid', placeItems: 'center', flex: '0 0 auto' }}>{FI.bolt}</span>
        <div style={{ flex: 1 }}><div style={{ fontWeight: 700, fontSize: 15 }}>Monitoring is on</div><div style={{ fontSize: 13, color: 'var(--ink-2)' }}>We watch for conflicting filings and upcoming deadlines across your portfolio, and alert you in plain English.</div></div>
        <button className="btn btn-ghost btn-sm" onClick={() => pushToast('Monitoring settings…')}>Settings</button>
      </div>
    </div></div>
  );
}

/* ============================ F6 · THE VAULT ============================ */
function Vault({ pushToast }) {
  const [open, setOpen] = useState(null);
  const item = VAULT.find((v) => v.id === open);
  useEffect(() => {
    const esc = (e) => { if (e.key === 'Escape') setOpen(null); };
    window.addEventListener('keydown', esc); return () => window.removeEventListener('keydown', esc);
  }, []);
  return (
    <div className="fscroll scrollbar-thin"><div className="fwrap">
      <div className="vault-band">
        <span className="grain" />
        <span className="shield">{FI.shield}</span>
        <div><h2>The Vault</h2><p>Every asset here is sealed with a tamper-proof proof-of-creation certificate — timestamped, hashed, and independently verifiable.</p></div>
        <div className="vstat">
          <div className="vs"><b>{VAULT.length}</b><span>Sealed</span></div>
          <div className="vs"><b>AES-256</b><span>Encrypted</span></div>
        </div>
      </div>

      <div className="vault-grid">
        {VAULT.map((v) => (
          <div className="vcard" key={v.id} onClick={() => setOpen(v.id)}>
            <div className="vtop">
              <span className="ext">{v.ext}</span>
              <div style={{ flex: 1, minWidth: 0 }}><div className="vn" style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{v.name}</div><div className="vk">{v.kind} · {v.size}</div></div>
              <span className="seal" title="Sealed">{FI.lock}</span>
            </div>
            <div className="vbody">
              <div className="hashwrap">
                <div className="hl">SHA-256</div>
                <div className="hash">{v.hash}</div>
                <div className="sealed">Sealed {v.sealed}</div>
              </div>
              <span className="qr"><QR seed={v.hash} /></span>
            </div>
          </div>
        ))}
      </div>
    </div>

      {item && <CertSheet item={item} onClose={() => setOpen(null)} pushToast={pushToast} />}
    </div>
  );
}

function CertSheet({ item, onClose, pushToast }) {
  return (
    <React.Fragment>
      <div className="scrim" onClick={onClose} />
      <div className="sheet scrollbar-thin" role="dialog" aria-modal="true">
        <div className="sh-head"><span className="t">Proof of creation</span><button className="sh-x" onClick={onClose} aria-label="Close">✕</button></div>
        <div className="cert">
          <div className="cband">
            <span className="grain" />
            <span className="cseal">{FI.shield}</span>
            <div><div className="ct">Certificate of creation</div><div className="cs">Lectual Vault · {item.certId}</div></div>
          </div>
          <div className="cbody">
            <div className="qrbig"><QR seed={item.hash} modules={25} /></div>
            <div className="qcap">Scan to verify · vault.lectual.com/v/{item.certId}</div>
            <div className="crow"><span className="ck">Asset</span><span className="cv">{item.name}</span></div>
            <div className="crow"><span className="ck">Type</span><span className="cv">{item.kind} · {item.ext}</span></div>
            <div className="crow"><span className="ck">Sealed</span><span className="cv">{item.sealed}</span></div>
            <div className="crow"><span className="ck">Owner</span><span className="cv">{F.name} · {F.company}</span></div>
            <div className="crow"><span className="ck">SHA-256</span><span className="cv mono">{item.hash}</span></div>
            {item.registered && <div className="crow"><span className="ck">Registration</span><span className="cv" style={{ color: 'var(--protected)' }}>Copyright registered</span></div>}
          </div>
          <div className="cfoot">
            <button className="btn btn-primary btn-sm" style={{ flex: 1 }} onClick={() => pushToast('Certificate PDF downloaded')}>{I.download} Download PDF</button>
            <button className="btn btn-secondary btn-sm" onClick={() => pushToast('Verification link copied')}>{FI.copy} Copy link</button>
          </div>
        </div>
        <div className="cnote">{FI.server}<span>This certificate proves the file existed in this exact form at the sealed timestamp. It is not a government registration on its own — your attorney advises on formal filings.</span></div>
      </div>
    </React.Fragment>
  );
}

/* ============================ F7 · MY COACH ============================ */
function Coach({ go }) {
  const [msgs, setMsgs] = useState(window.FOUNDER_COACH_SEED);
  const [typing, setTyping] = useState(false);
  const [draft, setDraft] = useState('');
  const threadRef = useRef(null);
  useEffect(() => { const el = threadRef.current; if (el) el.scrollTop = el.scrollHeight; }, [msgs, typing]);

  const ask = (text) => {
    if (!text.trim()) return;
    setMsgs((m) => [...m, { role: 'user', text }]);
    setDraft('');
    setTyping(true);
    setTimeout(() => {
      const reply = COACH_REPLIES[text] || { text: 'Great question. The short version: protecting your work usually comes down to picking the right type of protection (trademark vs copyright), filing in the categories you actually use, and keeping an eye on deadlines. Want me to map that to Pathset specifically? For anything case-specific, Dana is your person.' };
      setMsgs((m) => [...m, { role: 'ai', ...reply }]);
      setTyping(false);
    }, 1100);
  };

  return (
    <div className="coach">
      <div className="coach-guard">{FI.no}<span><b>Educational guidance, not legal advice.</b> For decisions about your situation, talk to your attorney.</span><a onClick={() => go('dashboard')}>Book Dana →</a></div>
      <div className="thread scrollbar-thin" ref={threadRef}>
        <div className="thread-in">
          {msgs.map((m, i) => (
            <div className={'msg ' + m.role} key={i}>
              <span className="mav">{m.role === 'ai' ? I.spark : F.initials}</span>
              <div>
                {m.tool && (
                  <div className="toolcard">
                    <span className="ti">{FI.bolt}</span>
                    <div style={{ flex: 1 }}>
                      <div className="tn">{m.tool.name}</div>
                      <div className="td">{m.tool.detail}</div>
                      <div className="tres">{I.check}{m.tool.result}</div>
                    </div>
                  </div>
                )}
                <div className="bubble">{m.text}</div>
              </div>
            </div>
          ))}
          {typing && (
            <div className="msg ai"><span className="mav">{I.spark}</span><div className="bubble"><div className="typing"><i /><i /><i /></div></div></div>
          )}
        </div>
      </div>
      <div className="composer">
        <div className="composer-in">
          <div className="prompts">
            {PROMPTS.map((p) => <button className="prompt-chip" key={p} onClick={() => ask(p)}>{p}</button>)}
          </div>
          <div className="cbox">
            <input placeholder="Ask anything about protecting Pathset…" value={draft} onChange={(e) => setDraft(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter') ask(draft); }} />
            <button className="send" onClick={() => ask(draft)} aria-label="Send">{FI.send}</button>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { FI, QR, Dashboard, Portfolio, Vault, Coach });
