// Additional screens: my runs, account, experts list, become-expert, about, auth, error states
//
// T4c: screens that need user data load via window.AppData.* in useEffect and
// render their own loading state. No synchronous reads of EXPERT/WORKAPP/
// RELATED/RUN_STEPS/RESULT. AuthScreen posts to /api/auth/magic-link.

const { useState: useState_m, useEffect: useEffect_m } = React;

// Normalize a run row returned by /api/app/me/runs into the shape the JSX
// below expects. The API gives us {id, workapp_id, workapp_slug, status,
// saved, share_token, created_at, completed_at} — analytics-style fields
// (workapp title, expert name, verdict, target) aren't on this endpoint
// yet, so they're stubbed so the layout still renders.
function _normRunRow(r) {
  if (!r) return null;
  const created = r.completed_at || r.created_at;
  const date = created ? new Date(created) : null;
  const days = date ? Math.floor((Date.now() - date.getTime()) / 86400000) : 0;
  const ago = (() => {
    if (!date) return '';
    if (days <= 0) return 'just now';
    if (days === 1) return '1 day ago';
    if (days < 7) return days + ' days ago';
    if (days < 14) return '1 week ago';
    if (days < 30) return Math.floor(days / 7) + ' weeks ago';
    return Math.floor(days / 30) + ' months ago';
  })();
  const expertName = r.expert || '';
  return {
    id: r.id,
    workapp: r.workapp_title || r.workapp || r.workapp_slug || 'WorkApp run',
    workappSlug: r.workapp_slug || '',
    expert: expertName,
    initial: expertName ? expertName.trim().charAt(0).toUpperCase() : '·',
    bg: (window.AppData && window.AppData.gradientFor)
      ? window.AppData.gradientFor(expertName || r.workapp_slug || 'run')
      : 'linear-gradient(135deg, #6b8e7f, #2d4a3a)',
    target: r.target || r.input_url || '—',
    verdict: r.verdict || (r.status === 'running' ? 'In progress…' : ''),
    date: date ? date.toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' }) : '',
    ago: ago,
    daysAgo: days,
    status: r.status === 'complete' || r.status === 'completed' ? 'complete' : (r.status || 'running'),
  };
}

// ─────────────────────────────────────────────────────────────────────
// MY RUNS — signed-in user's run history
// ─────────────────────────────────────────────────────────────────────
function MyRunsScreen({ onOpenResult, onWorkApp, signedIn, onRequireAuth }) {
  const [filter, setFilter] = useState_m('all');
  const [runs, setRuns] = useState_m(null);    // null = loading, [] = empty
  const [loadError, setLoadError] = useState_m(null);

  useEffect_m(() => {
    if (!signedIn) return;
    let cancelled = false;
    window.AppData.myRuns()
      .then((rows) => {
        if (cancelled) return;
        setRuns((rows || []).map(_normRunRow).filter(Boolean));
      })
      .catch((err) => {
        if (cancelled) return;
        if (err && err.status === 401) { window.AppData.redirectToLogin(); return; }
        setLoadError(err);
        setRuns([]);
      });
    return () => { cancelled = true; };
  }, [signedIn]);

  if (!signedIn) {
    return (
      <div data-screen-label="10 My Runs (Locked)">
        <div className="wrap" style={{maxWidth: 720, paddingTop: 80}}>
          <div className="section-label">Your library</div>
          <h1 className="serif" style={{fontSize: 56, lineHeight: 1.05, letterSpacing: '-0.025em', margin: '12px 0 18px'}}>Sign in to see <em>your runs</em>.</h1>
          <p style={{fontSize: 18, color: 'var(--ink-2)', lineHeight: 1.55, marginBottom: 32, maxWidth: 560}}>
            Every WorkApp you run gets saved to your library — verdict, evidence, and the full trace. Rerun any time something changes.
          </p>
          <button className="btn btn-primary btn-lg" onClick={() => onRequireAuth('Sign in to see your run history')}>
            Sign in <Icon.ArrowRight />
          </button>
        </div>
        <Footer />
      </div>
    );
  }

  if (runs === null) {
    return <div className="loading" style={{padding: 40}}>Loading your runs…</div>;
  }

  if (loadError) {
    return (
      <div data-screen-label="10 My Runs (Error)">
        <div className="wrap" style={{maxWidth: 720, paddingTop: 80}}>
          <h1 className="serif" style={{fontSize: 40, margin: '0 0 12px'}}>Couldn't load your runs.</h1>
          <p style={{color: 'var(--muted)'}}>{String(loadError.message || loadError)}</p>
        </div>
        <Footer />
      </div>
    );
  }

  const targets = [...new Set(runs.map(r => r.target).filter(t => t && t !== '—'))];
  const filtered = filter === 'all' ? runs : runs.filter(r => r.target === filter);

  return (
    <div data-screen-label="10 My Runs">
      <div className="wrap">
        <div style={{paddingTop: 56, paddingBottom: 24}}>
          <div className="section-label">Your library</div>
          <h1 className="serif" style={{fontSize: 48, lineHeight: 1.05, letterSpacing: '-0.025em', margin: '8px 0 12px'}}>My runs</h1>
          <p style={{fontSize: 16, color: 'var(--muted)', margin: 0}}>
            {runs.length} {runs.length === 1 ? 'run' : 'runs'}
            {targets.length > 0 ? ` across ${targets.length} ${targets.length === 1 ? 'company' : 'companies'}.` : '.'}
          </p>
        </div>

        {runs.length === 0 ? (
          <div style={{padding: '64px 0', textAlign: 'center'}}>
            <h2 className="serif" style={{fontSize: 28, margin: '0 0 12px'}}>No runs yet.</h2>
            <p style={{color: 'var(--muted)', margin: '0 0 24px'}}>Pick a WorkApp and run it on your company — the verdict will land here.</p>
            <button className="btn btn-primary" onClick={onWorkApp}>Browse WorkApps <Icon.ArrowRight /></button>
          </div>
        ) : (
          <>
            {targets.length > 0 && (
              <div style={{display: 'flex', gap: 8, alignItems: 'center', padding: '14px 0', borderTop: '1px solid var(--hair)', borderBottom: '1px solid var(--hair)', flexWrap: 'wrap'}}>
                <span style={{fontFamily: 'Geist Mono, monospace', fontSize: 11, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--muted)', marginRight: 8}}>Company</span>
                <button className={'chip' + (filter === 'all' ? ' chip-active' : '')} onClick={() => setFilter('all')}>All ({runs.length})</button>
                {targets.map(t => (
                  <button key={t} className={'chip' + (filter === t ? ' chip-active' : '')} onClick={() => setFilter(t)}>
                    {t} ({runs.filter(r => r.target === t).length})
                  </button>
                ))}
              </div>
            )}

            <div className="runs-list">
              {filtered.map(r => {
                const dueForRerun = r.status === 'complete' && r.daysAgo >= 7;
                return (
                  <div key={r.id} className="run-row-wrap">
                    <button className="run-row" onClick={() => onOpenResult(r)}>
                      <ExpertAvatar person={r} name={r.expert} style={{width: 38, height: 38, fontSize: 14, background: r.bg, flexShrink: 0}} />
                      <div className="run-row-main">
                        <div className="run-row-head">
                          <span className="run-row-title">{r.workapp}</span>
                          {r.target && r.target !== '—' && <span className="run-row-target">on {r.target}</span>}
                          {dueForRerun && <span className="run-row-due">Due for re-run</span>}
                        </div>
                        {r.verdict && <div className="run-row-verdict">{r.verdict}</div>}
                        <div className="run-row-meta">
                          {r.expert && <><span>by {r.expert}</span><span>·</span></>}
                          <span>{r.ago}</span>
                          {r.status === 'running' && <span className="run-row-running">● Running</span>}
                        </div>
                      </div>
                      <Icon.ArrowRight className="run-row-arrow" />
                    </button>
                    {r.status === 'complete' && (
                      <button
                        className={'run-row-rerun' + (dueForRerun ? ' run-row-rerun-due' : '')}
                        onClick={(ev) => { ev.stopPropagation(); onOpenResult(r, { rerun: true }); }}
                        title={`Last run ${r.ago} — re-run to see what changed`}
                      >
                        <Icon.Refresh className="icon-sm" />
                        <span>Re-run</span>
                      </button>
                    )}
                  </div>
                );
              })}
            </div>
          </>
        )}

        <div style={{marginTop: 48, padding: '32px 0', borderTop: '1px solid var(--hair)', textAlign: 'center'}}>
          <p style={{fontSize: 15, color: 'var(--muted)', margin: '0 0 14px'}}>Looking for a different diagnostic?</p>
          <button className="btn btn-ghost" onClick={onWorkApp}>Browse WorkApps <Icon.ArrowRight /></button>
        </div>
      </div>
      <Footer />
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────
// ACCOUNT — workspace settings
// ─────────────────────────────────────────────────────────────────────
function AccountScreen({ signedIn, onSignOut, onRequireAuth }) {
  const [user, setUser] = useState_m(null);
  const [loadError, setLoadError] = useState_m(null);
  const [name, setName] = useState_m('');
  const [workspace, setWorkspace] = useState_m('');
  const [domain, setDomain] = useState_m('');
  const [emailDigest, setEmailDigest] = useState_m(true);
  const [shareAlerts, setShareAlerts] = useState_m(true);
  const [saved, setSaved] = useState_m(false);
  const [deleteConfirm, setDeleteConfirm] = useState_m(false);

  useEffect_m(() => {
    if (!signedIn) return;
    let cancelled = false;
    window.AppData.me()
      .then((u) => {
        if (cancelled) return;
        setUser(u || {});
        setName((u && u.name) || '');
        setWorkspace((u && (u.workspace || u.companyName)) || '');
        setDomain((u && (u.defaultUrl || u.domain)) || '');
      })
      .catch((err) => {
        if (cancelled) return;
        if (err && err.status === 401) { window.AppData.redirectToLogin(); return; }
        setLoadError(err);
      });
    return () => { cancelled = true; };
  }, [signedIn]);

  useEffect_m(() => {
    if (!signedIn) return;
    let cancelled = false;
    fetch('/api/app/me/profile', { credentials: 'include' })
      .then((r) => r.ok ? r.json() : Promise.reject(r))
      .then((profile) => {
        if (cancelled) return;
        if (profile.name) setName(profile.name);
        if (profile.company) setWorkspace(profile.company);
        if (profile.defaultUrl) setDomain(profile.defaultUrl);
        if (typeof profile.notifDigest === 'boolean') setEmailDigest(profile.notifDigest);
        if (typeof profile.notifShare === 'boolean') setShareAlerts(profile.notifShare);
      })
      .catch(() => { /* non-critical — silently ignore */ });
    return () => { cancelled = true; };
  }, [signedIn]);

  if (!signedIn) {
    return (
      <div data-screen-label="11 Account (Locked)">
        <div className="wrap" style={{maxWidth: 720, paddingTop: 80}}>
          <div className="section-label">Account</div>
          <h1 className="serif" style={{fontSize: 56, lineHeight: 1.05, letterSpacing: '-0.025em', margin: '12px 0 18px'}}>Sign in to manage <em>your account</em>.</h1>
          <button className="btn btn-primary btn-lg" onClick={() => onRequireAuth('Sign in to access your account')}>
            Sign in <Icon.ArrowRight />
          </button>
        </div>
        <Footer />
      </div>
    );
  }

  if (!user && !loadError) {
    return <div className="loading" style={{padding: 40}}>Loading your account…</div>;
  }

  if (loadError) {
    return (
      <div data-screen-label="11 Account (Error)">
        <div className="wrap" style={{maxWidth: 720, paddingTop: 80}}>
          <h1 className="serif" style={{fontSize: 40, margin: '0 0 12px'}}>Couldn't load your account.</h1>
          <p style={{color: 'var(--muted)'}}>{String(loadError.message || loadError)}</p>
        </div>
        <Footer />
      </div>
    );
  }

  const email = (user && user.email) || '';

  const save = async function(ev) {
    ev.preventDefault();
    try {
      await fetch('/api/app/me/profile', {
        method: 'POST',
        credentials: 'include',
        headers: { 'Content-Type': 'application/json', 'x-csrf-token': '1' },
        body: JSON.stringify({
          name: name,
          company: workspace,
          defaultUrl: domain,
          notifDigest: emailDigest,
          notifShare: shareAlerts,
        }),
      });
      setSaved(true);
      setTimeout(function() { setSaved(false); }, 2000);
    } catch (e) {
      console.error('Profile save failed', e);
    }
  };

  const handleSignOut = async () => {
    try {
      await fetch('/api/auth/sign-out', { method: 'POST', credentials: 'include' });
    } catch (e) {
      // Best effort — fall through to redirect either way.
    }
    if (typeof onSignOut === 'function') onSignOut();
    window.location.href = '/';
  };

  return (
    <div data-screen-label="11 Account">
      <div className="wrap" style={{maxWidth: 760}}>
        <div style={{paddingTop: 56, paddingBottom: 32}}>
          <div className="section-label">Account</div>
          <h1 className="serif" style={{fontSize: 48, lineHeight: 1.05, letterSpacing: '-0.025em', margin: '8px 0 0'}}>Settings</h1>
        </div>

        {user && user.email && (user.email.endsWith('@silverbee.ai') || user.email.endsWith('@anthropic.com')) && (
          <div style={{padding: 14, marginBottom: 24, background: 'color-mix(in srgb, var(--accent) 5%, transparent)', borderRadius: 'var(--r-md)', fontSize: 13}}>
            <b>Author tools:</b> to publish a built workapp to the marketplace, open <code>#/publish/&lt;workapp-id&gt;</code>. The builder agent surfaces this link automatically when you ask it to "publish as content".
          </div>
        )}
        <form onSubmit={save}>
          <div className="acc-section">
            <div className="acc-section-h">Profile</div>
            <div className="field">
              <label className="field-label">Name</label>
              <input className="input" value={name} onChange={(ev) => setName(ev.target.value)} />
            </div>
            <div className="field">
              <label className="field-label">Email</label>
              <input className="input" value={email} disabled style={{opacity: 0.6}} />
              <div style={{fontSize: 12, color: 'var(--muted)', marginTop: 6}}>Sign-in email — contact support to change.</div>
            </div>
          </div>

          <div className="acc-section">
            <div className="acc-section-h">Workspace</div>
            <div className="field">
              <label className="field-label">Company name</label>
              <input className="input" value={workspace} onChange={(ev) => setWorkspace(ev.target.value)} />
            </div>
            <div className="field">
              <label className="field-label">Default URL for runs</label>
              <input className="input" value={domain} onChange={(ev) => setDomain(ev.target.value)} />
              <div style={{fontSize: 12, color: 'var(--muted)', marginTop: 6}}>We'll prefill this in run forms.</div>
            </div>
          </div>

          <div className="acc-section">
            <div className="acc-section-h">Notifications</div>
            <label className="acc-toggle">
              <input type="checkbox" checked={emailDigest} onChange={(ev) => setEmailDigest(ev.target.checked)} />
              <div>
                <div className="acc-toggle-h">Weekly email digest</div>
                <div className="acc-toggle-sub">New WorkApps from experts you've run.</div>
              </div>
            </label>
            <label className="acc-toggle">
              <input type="checkbox" checked={shareAlerts} onChange={(ev) => setShareAlerts(ev.target.checked)} />
              <div>
                <div className="acc-toggle-h">Share activity</div>
                <div className="acc-toggle-sub">When someone views or comments on a result you shared.</div>
              </div>
            </label>
          </div>

          <div className="acc-section" style={{borderBottom: 0}}>
            <div className="acc-section-h">Danger zone</div>
            <div style={{display: 'flex', gap: 12, flexWrap: 'wrap'}}>
              <button type="button" className="btn btn-ghost" onClick={handleSignOut}>Sign out</button>
              <button type="button" className="btn btn-ghost" style={{color: '#a13a2e'}} onClick={() => setDeleteConfirm(!deleteConfirm)}>Delete account</button>
            </div>
            {deleteConfirm && (
              <div className="danger-confirm">
                Account deletion is currently handled by support to ensure your runs and exports are preserved. Email <a href="mailto:support@workapp.ai" style={{color: 'var(--accent)'}}>support@workapp.ai</a> and we'll process it within 7 days.
              </div>
            )}
          </div>

          <div style={{display: 'flex', gap: 12, alignItems: 'center', paddingTop: 24, borderTop: '1px solid var(--hair)'}}>
            <button type="submit" className="btn btn-primary">Save changes</button>
            {saved && <span style={{fontSize: 13, color: 'var(--good)'}}>✓ Saved</span>}
          </div>
        </form>
      </div>
      <Footer />
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────
// EXPERT DIRECTORY
// ─────────────────────────────────────────────────────────────────────
// Map API expertCard → the shape this directory expects. The API stub
// doesn't yet emit category/runs/workApps counts, so they degrade to a
// neutral default ('Other' / 0 / '—') and search just covers what's
// available (name, title, specialty).
function _normExpertForDirectory(e) {
  if (!e) return null;
  return {
    name: e.name || '',
    initial: e.initial || ((e.name || '?').trim().charAt(0).toUpperCase()),
    photo: e.photo,
    bg: e.avatarBg || e.bg || 'linear-gradient(135deg, #6b8e7f, #2d4a3a)',
    title: e.title || e.role || '',
    specialty: e.specialty || e.proofLine || '',
    cat: e.cat || e.category || 'Other',
    workApps: e.workAppsCount || e.workApps || 0,
    workAppTitles: e.workAppTitles || [],
    runs: e.totalRuns || e.runs || '—',
    runsNum: typeof e.runsNum === 'number' ? e.runsNum : 0,
    featured: !!e.featured,
    joined: e.joined || '',
    isNew: !!e.isNew,
    bio: e.bio || '',
  };
}

function ExpertsDirectoryScreen({ onExpert, onBecomeExpert }) {
  const [q, setQ] = useState_m('');
  const [cat, setCat] = useState_m('All');
  const [sort, setSort] = useState_m('featured');
  const [experts, setExperts] = useState_m(null);     // null = loading
  const [loadError, setLoadError] = useState_m(null);

  useEffect_m(() => {
    let cancelled = false;
    window.AppData.listExperts()
      .then((list) => {
        if (cancelled) return;
        setExperts((list || []).map(_normExpertForDirectory).filter(Boolean));
      })
      .catch((err) => {
        if (cancelled) return;
        setLoadError(err);
        setExperts([]);
      });
    return () => { cancelled = true; };
  }, []);

  if (experts === null) {
    return <div className="loading" style={{padding: 40}}>Loading experts…</div>;
  }

  const filtered = experts.filter(e => {
    if (cat !== 'All' && e.cat !== cat) return false;
    if (!q) return true;
    const s = (q || '').toLowerCase();
    return (e.name || '').toLowerCase().includes(s) ||
      (e.title || '').toLowerCase().includes(s) ||
      (e.specialty || '').toLowerCase().includes(s) ||
      (e.cat || '').toLowerCase().includes(s) ||
      (e.workAppTitles || []).some(t => (t || '').toLowerCase().includes(s));
  });

  const sorted = [...filtered].sort((a, b) => {
    if (sort === 'featured') {
      if (a.featured !== b.featured) return a.featured ? -1 : 1;
      return (b.runsNum || 0) - (a.runsNum || 0);
    }
    if (sort === 'runs') return (b.runsNum || 0) - (a.runsNum || 0);
    if (sort === 'newest') return new Date(b.joined || 0) - new Date(a.joined || 0);
    if (sort === 'name') return (a.name || '').localeCompare(b.name || '');
    return 0;
  });

  // Categories derived from the loaded experts; 'All' always first.
  const dynamicCats = ['All', ...Array.from(new Set(experts.map(e => e.cat).filter(Boolean)))];

  const showFeaturedRail = !q && cat === 'All' && sort === 'featured';
  const featured = experts.filter(e => e.featured);
  const display = showFeaturedRail ? sorted.filter(e => !e.featured) : sorted;

  const counts = dynamicCats.reduce((acc, c) => {
    acc[c] = c === 'All' ? experts.length : experts.filter(e => e.cat === c).length;
    return acc;
  }, {});

  const reset = () => { setQ(''); setCat('All'); setSort('featured'); };

  return (
    <div data-screen-label="12 Experts">
      <div className="wrap">
        <div style={{paddingTop: 56, paddingBottom: 24}}>
          <h1 className="serif" style={{fontSize: 56, lineHeight: 1.05, letterSpacing: '-0.025em', margin: '0 0 16px', maxWidth: 760}}>The people behind the <em>expertise.</em></h1>
          <p style={{fontSize: 18, color: 'var(--ink-2)', lineHeight: 1.55, margin: 0, maxWidth: 640}}>
            Every WorkApp encodes one expert's framework. {experts.length} {experts.length === 1 ? 'expert' : 'experts'}. Browse by specialty, search their methods, run their thinking.
          </p>
        </div>

        {loadError && (
          <div style={{padding: 16, background: 'color-mix(in srgb, #a13a2e 8%, transparent)', border: '1px solid color-mix(in srgb, #a13a2e 30%, transparent)', borderRadius: 'var(--r-md)', marginBottom: 16, fontSize: 14}}>
            Couldn't load experts: {String(loadError.message || loadError)}
          </div>
        )}

        {experts.length === 0 ? (
          <div className="experts-empty" style={{padding: '48px 0'}}>
            <h3 className="serif">No experts yet.</h3>
            <p>Check back soon — we onboard practitioners one at a time.</p>
          </div>
        ) : (
          <>
            <div className="search-row" style={{marginTop: 16}}>
              <Icon.Search className="search-icon" />
              <input
                className="search-input"
                placeholder="Search by name, specialty, or WorkApp"
                value={q}
                onChange={(ev) => setQ(ev.target.value)}
              />
              <span className="search-count">{sorted.length} {sorted.length === 1 ? 'expert' : 'experts'}</span>
            </div>

            <div className="experts-toolbar">
              <div className="experts-cats">
                {dynamicCats.map(c => (
                  <button
                    key={c}
                    className={'chip' + (cat === c ? ' chip-active' : '')}
                    onClick={() => setCat(c)}
                    disabled={counts[c] === 0}
                  >
                    {c}
                  </button>
                ))}
              </div>
              <div className="experts-sort">
                <label>Sort</label>
                <select value={sort} onChange={(ev) => setSort(ev.target.value)}>
                  <option value="featured">Featured</option>
                  <option value="runs">Most run</option>
                  <option value="newest">Newest</option>
                  <option value="name">A–Z</option>
                </select>
              </div>
            </div>

            {showFeaturedRail && featured.length > 0 && (
              <div className="experts-featured">
                <div className="experts-rail-label">Featured this week</div>
                <div className="experts-featured-grid">
                  {featured.map((e, i) => (
                    <button key={i} className="expert-card-feat" onClick={() => onExpert(e)}>
                      <ExpertAvatar person={e} style={{width: 64, height: 64, fontSize: 26, background: e.bg}} />
                      <div>
                        <div className="expert-card-name" style={{fontSize: 22}}>{e.name}</div>
                        <div className="expert-card-title">{e.title}</div>
                        <p className="expert-card-spec" style={{margin: '10px 0 14px', fontSize: 14, lineHeight: 1.5, color: 'var(--ink-2)'}}>{e.specialty}</p>
                        <div className="expert-card-stats">
                          <span><b>{e.workApps}</b> WorkApps</span>
                          {e.runs && e.runs !== '—' ? <><span>·</span><span><b>{e.runs}</b> runs</span></> : null}
                        </div>
                      </div>
                    </button>
                  ))}
                </div>
              </div>
            )}

            {display.length > 0 && (
              <div className="experts-rail-label" style={{marginTop: showFeaturedRail && featured.length > 0 ? 40 : 24}}>
                {showFeaturedRail && featured.length > 0 ? 'All experts' : `${sorted.length} ${sorted.length === 1 ? 'expert' : 'experts'}`}
              </div>
            )}

            <div className="experts-grid-2">
              {display.map((e, i) => (
                <button key={i} className="expert-card-2" onClick={() => onExpert(e)}>
                  <div className="expert-card-2-head">
                    <ExpertAvatar person={e} style={{width: 52, height: 52, fontSize: 19, background: e.bg, flexShrink: 0}} />
                    <div className="expert-card-2-identity">
                      <div className="expert-card-2-name">
                        {e.name}
                        {e.isNew && <span className="badge-new">NEW</span>}
                      </div>
                      <div className="expert-card-2-title">{e.title}</div>
                    </div>
                  </div>
                  <div className="expert-card-2-spec">{e.specialty}</div>
                  {(e.workAppTitles || []).length > 0 && (
                    <div className="expert-card-2-wapps">
                      {(e.workAppTitles || []).slice(0, 2).map((t, j) => (
                        <span key={j} className="wapp-chip">{t}</span>
                      ))}
                      {(e.workAppTitles || []).length > 2 && (
                        <span className="wapp-chip wapp-chip-more">+{e.workAppTitles.length - 2}</span>
                      )}
                    </div>
                  )}
                  <div className="expert-card-2-foot">
                    <div className="expert-card-2-meta">
                      {e.cat && e.cat !== 'Other' ? <span className="expert-card-2-cat">{e.cat}</span> : null}
                      <span><b>{e.workApps}</b> {e.workApps === 1 ? 'WorkApp' : 'WorkApps'}{e.runs && e.runs !== '—' ? ` · ${e.runs} runs` : ''}</span>
                    </div>
                    <span className="expert-card-action">View profile <Icon.ArrowRight className="icon-sm" /></span>
                  </div>
                </button>
              ))}
            </div>

            {sorted.length === 0 && (
              <div className="experts-empty">
                <h3 className="serif">No experts match these filters.</h3>
                <p>Try broadening your search, or clearing filters to see all {experts.length} practitioners.</p>
                <button className="btn btn-ghost btn-sm" onClick={reset}>Clear filters</button>
              </div>
            )}
          </>
        )}

        <div style={{padding: '56px 0 24px', borderTop: '1px solid var(--hair)', marginTop: 56, textAlign: 'center'}}>
          <p style={{fontSize: 15, color: 'var(--muted)', margin: '0 0 14px'}}>Are you a practitioner with a method worth running?</p>
          <button className="btn btn-ghost" onClick={onBecomeExpert}>Apply to be an expert <Icon.ArrowRight /></button>
        </div>
      </div>
      <Footer />
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────
// BECOME AN EXPERT — waiting list landing
// ─────────────────────────────────────────────────────────────────────
function BecomeExpertScreen({ onSubmit }) {
  const [name, setName] = useState_m('');
  const [email, setEmail] = useState_m('');
  const [link, setLink] = useState_m('');
  const [pitch, setPitch] = useState_m('');
  const [submitted, setSubmitted] = useState_m(false);
  const [errors, setErrors] = useState_m({});

  const submit = (ev) => {
    ev.preventDefault();
    const errs = {};
    if (!name.trim()) errs.name = 'Required.';
    if (!email.trim()) errs.email = 'Required.';
    else if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) errs.email = 'Use a valid email.';
    if (!link.trim()) errs.link = 'Required — share a link to your method, book, or talk.';
    else if (!/^https?:\/\/\S+\.\S+/i.test(link.trim())) errs.link = 'Must be a valid URL starting with http:// or https://';
    setErrors(errs);
    if (Object.keys(errs).length === 0) {
      const formData = { name: name.trim(), email: email.trim(), link: link.trim(), pitch: pitch.trim() };
      if (window.AppData && typeof window.AppData.logIntent === 'function') {
        window.AppData.logIntent('become_expert', formData);
      }
      if (typeof onSubmit === 'function') onSubmit(formData);
      setSubmitted(true);
    }
  };

  if (submitted) {
    return (
      <div data-screen-label="13 Become Expert (Submitted)">
        <div className="wrap" style={{maxWidth: 640, paddingTop: 96, textAlign: 'center'}}>
          <div style={{display: 'inline-flex', width: 56, height: 56, borderRadius: '50%', background: 'color-mix(in srgb, var(--accent) 12%, transparent)', color: 'var(--accent)', alignItems: 'center', justifyContent: 'center', marginBottom: 24}}>
            <Icon.Check />
          </div>
          <h1 className="serif" style={{fontSize: 48, lineHeight: 1.1, letterSpacing: '-0.022em', margin: '0 0 16px'}}>You're on the list.</h1>
          <p style={{fontSize: 17, color: 'var(--ink-2)', lineHeight: 1.55, marginBottom: 28}}>
            We onboard experts manually, one at a time, so the editorial bar stays high. Expect to hear from us within two weeks if your method fits the V1 cohort.
          </p>
          <p style={{fontSize: 14, color: 'var(--muted)', lineHeight: 1.5}}>
            In the meantime — if you have a published framework, send the link. It's how we evaluate.
          </p>
        </div>
        <Footer />
      </div>
    );
  }

  return (
    <div data-screen-label="13 Become Expert">
      <div className="wrap" style={{maxWidth: 760}}>
        <div style={{paddingTop: 56, paddingBottom: 28}}>
          <div className="section-label">For experts</div>
          <h1 className="serif" style={{fontSize: 56, lineHeight: 1.05, letterSpacing: '-0.025em', margin: '8px 0 16px'}}>Turn your framework into a <em>WorkApp.</em></h1>
          <p style={{fontSize: 18, color: 'var(--ink-2)', lineHeight: 1.55, margin: 0, maxWidth: 640}}>
            If you have a method buyers ask you to run on their company, we'll help you turn it into a runnable diagnostic. No code. No platform-builder UI. We onboard you ourselves.
          </p>
        </div>

        <div className="be-grid">
          <div>
            <h3 className="serif" style={{fontSize: 22, fontWeight: 500, letterSpacing: '-0.012em', margin: '0 0 14px'}}>What we're looking for</h3>
            <ul className="be-list">
              <li><b>A repeatable method.</b> Something you've run for at least 5–10 clients and can describe step by step.</li>
              <li><b>A narrow output.</b> One verdict, one recommendation. Not a 30-page audit.</li>
              <li><b>Willingness to be the brand.</b> Your name and method anchor the WorkApp. We don't whitelabel.</li>
            </ul>
          </div>
          <div>
            <h3 className="serif" style={{fontSize: 22, fontWeight: 500, letterSpacing: '-0.012em', margin: '0 0 14px'}}>What you get</h3>
            <ul className="be-list">
              <li>A distribution surface where the work itself is the marketing.</li>
              <li>Inbound leads. Buyers appreciate your thinking before contacting you.</li>
              <li>Editorial collaboration. We'll help you encode the method clearly.</li>
            </ul>
          </div>
        </div>

        <form onSubmit={submit} className="side-card" style={{padding: 32, marginTop: 48}}>
          <div style={{display: 'flex', alignItems: 'center', gap: 8, marginBottom: 14}}>
            <span style={{width: 6, height: 6, borderRadius: '50%', background: 'var(--accent)'}}></span>
            <span style={{fontFamily: 'Geist Mono, monospace', fontSize: 11, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--accent)'}}>Apply to publish</span>
          </div>
          <h3 style={{margin: '0 0 6px', fontFamily: 'Inter Tight, Geist, ui-sans-serif, system-ui, sans-serif', fontSize: 24, fontWeight: 700, letterSpacing: '-0.014em'}}>Tell us about your method</h3>
          <p style={{margin: '0 0 22px', fontSize: 14, color: 'var(--muted)', lineHeight: 1.5}}>We read every application. Reply within ~2 weeks.</p>

          <div className="field">
            <label className="field-label">Your name <span style={{color: 'var(--accent)'}}>*</span></label>
            <input className={'input' + (errors.name ? ' error' : '')} value={name} onChange={(ev) => setName(ev.target.value)} placeholder="Your name" />
            {errors.name && <div className="field-error"><Icon.Alert className="icon-sm" /> {errors.name}</div>}
          </div>

          <div className="field">
            <label className="field-label">Email <span style={{color: 'var(--accent)'}}>*</span></label>
            <input className={'input' + (errors.email ? ' error' : '')} value={email} onChange={(ev) => setEmail(ev.target.value)} placeholder="you@domain.com" />
            {errors.email && <div className="field-error"><Icon.Alert className="icon-sm" /> {errors.email}</div>}
          </div>

          <div className="field">
            <label className="field-label">Link to your method, book, or talk</label>
            <input className={'input' + (errors.link ? ' error' : '')} value={link} onChange={(ev) => { setLink(ev.target.value); if (errors.link) setErrors({...errors, link: undefined}); }} placeholder="https://" />
            {errors.link && <div className="field-error"><Icon.Alert className="icon-sm" /> {errors.link}</div>}
          </div>

          <div className="field">
            <label className="field-label">In one paragraph: what method would you turn into a WorkApp? <span style={{color: 'var(--accent)'}}>*</span></label>
            <textarea className={'textarea' + (errors.pitch ? ' error' : '')} value={pitch} onChange={(ev) => setPitch(ev.target.value)} rows={5} placeholder="The diagnostic question, who it's for, and what the output looks like." />
            {errors.pitch && <div className="field-error"><Icon.Alert className="icon-sm" /> {errors.pitch}</div>}
          </div>

          <button type="submit" className="btn btn-primary btn-lg" style={{marginTop: 8}}>
            Apply <Icon.ArrowRight />
          </button>
        </form>
      </div>
      <Footer />
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────
// ABOUT — What is a WorkApp
// ─────────────────────────────────────────────────────────────────────
function AboutScreen({ onWorkApp, onExperts, onBecomeExpert }) {
  return (
    <div data-screen-label="14 About">
      <div className="wrap" style={{maxWidth: 760}}>
        <div style={{paddingTop: 64, paddingBottom: 40}}>
          <div className="section-label">About</div>
          <h1 className="serif" style={{fontSize: 64, lineHeight: 1.04, letterSpacing: '-0.028em', margin: '8px 0 28px'}}>
            A blog gives you<br/>expert thinking <em>to read.</em><br/>A WorkApp gives you<br/>expert thinking <em>to run.</em>
          </h1>
          <p style={{fontSize: 19, color: 'var(--ink-2)', lineHeight: 1.55, margin: 0, maxWidth: 600}}>
            WorkApps are a new publishing format. Credible practitioners encode their methods as runnable diagnostics. You run them on your company. You get a verdict, evidence, and a single recommendation.
          </p>
        </div>

        <div style={{padding: '40px 0', borderTop: '1px solid var(--hair)'}}>
          <div className="section-label">The problem</div>
          <h2 className="h-section" style={{maxWidth: 640}}>Most expert content is stuck in read-only.</h2>
          <p style={{fontSize: 17, color: 'var(--ink-2)', lineHeight: 1.65, maxWidth: 640, margin: '0 0 16px'}}>
            You read a great essay on positioning. You think, "this is exactly what we need." Then you spend two weeks trying to apply it to your own homepage and the insight evaporates.
          </p>
          <p style={{fontSize: 17, color: 'var(--ink-2)', lineHeight: 1.65, maxWidth: 640, margin: 0}}>
            The expert had the framework. You had the company. The two never met. WorkApps fix that — by making the framework runnable on your inputs.
          </p>
        </div>

        <div style={{padding: '40px 0', borderTop: '1px solid var(--hair)'}}>
          <div className="section-label">How a WorkApp is built</div>
          <ol className="method-list" style={{maxWidth: 720}}>
            <li><div>
              <div className="method-step-title">An expert proposes a method</div>
              <div className="method-step-desc">A framework they've used 5–10+ times in client work. Narrow. Repeatable. Has a clear verdict.</div>
            </div></li>
            <li><div>
              <div className="method-step-title">We co-author the diagnostic</div>
              <div className="method-step-desc">Editorial sessions to encode the framework — what to read, what to compare, what to ignore. No code from the expert.</div>
            </div></li>
            <li><div>
              <div className="method-step-title">We run it on real companies</div>
              <div className="method-step-desc">Calibration runs against companies the expert knows well, until the verdict matches their human judgment.</div>
            </div></li>
            <li><div>
              <div className="method-step-title">It ships under the expert's name</div>
              <div className="method-step-desc">Their bio. Their voice. Their CTA. The platform is the surface, not the brand.</div>
            </div></li>
          </ol>
        </div>

        <div style={{padding: '48px 0', borderTop: '1px solid var(--hair)', display: 'grid', gap: 16}}>
          <div style={{display: 'flex', gap: 12, flexWrap: 'wrap'}}>
            <button className="btn btn-primary" onClick={onWorkApp}>Browse WorkApps <Icon.ArrowRight /></button>
            <button className="btn btn-ghost" onClick={onExperts}>Meet the experts</button>
            <button className="btn btn-ghost" onClick={onBecomeExpert}>I'm an expert →</button>
          </div>
        </div>
      </div>
      <Footer />
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────
// AUTH — sign in / sign up (magic link)
// ─────────────────────────────────────────────────────────────────────
function AuthScreen({ mode = 'signin', onSwitch }) {
  const [email, setEmail]           = useState_m('');
  const [name, setName]             = useState_m('');
  const [sent, setSent]             = useState_m(false);
  const [submitting, setSubmitting] = useState_m(false);
  const [sendErr, setSendErr]       = useState_m(null);
  const [errors, setErrors]         = useState_m({});
  const [otpCode, setOtpCode]       = useState_m('');
  const [verifying, setVerifying]   = useState_m(false);
  const [verifyErr, setVerifyErr]   = useState_m(null);
  const [resendCooldown, setResendCooldown] = useState_m(0);

  useEffect_m(() => {
    if (resendCooldown <= 0) return;
    var id = setTimeout(() => setResendCooldown(function(p) { return p - 1; }), 1000);
    return () => clearTimeout(id);
  }, [resendCooldown]);

  const submit = async (ev) => {
    ev.preventDefault();
    const errs = {};
    if (!email.trim()) errs.email = 'Required.';
    else if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) errs.email = 'Use a valid email.';
    if (mode === 'signup' && !name.trim()) errs.name = 'Required.';
    setErrors(errs);
    if (Object.keys(errs).length > 0) return;
    setSubmitting(true); setSendErr(null);
    try {
      await window.AppData.requestMagicLink(email.trim());
      setSent(true); setResendCooldown(30);
    } catch (e) { setSendErr(e); }
    finally { setSubmitting(false); }
  };

  const handleOtpChange = async (val) => {
    const digits = val.replace(/\D/g, '').slice(0, 6);
    setOtpCode(digits); setVerifyErr(null);
    if (digits.length === 6) {
      setVerifying(true);
      try {
        const data = await window.AppData.verifyMagicCode(email.trim(), digits);
        window.location.href = data.redirectUrl || '/';
      } catch (e) {
        setVerifyErr((e && e.message) ? e.message : 'Invalid or expired code. Please try again.');
        setOtpCode(''); setVerifying(false);
      }
    }
  };

  const handleResend = async () => {
    if (resendCooldown > 0 || verifying) return;
    setOtpCode(''); setVerifyErr(null);
    try {
      await window.AppData.requestMagicLink(email.trim());
      setResendCooldown(30);
    } catch (e) { setVerifyErr('Could not resend — please try again.'); }
  };

  const goSocial = (provider) => {
    var r = encodeURIComponent(window.location.pathname + window.location.search + window.location.hash);
    window.location.href = '/api/auth/social/' + provider + '?return_to=' + r;
  };

  return (
    <div data-screen-label={'15 Auth · ' + mode}>
      <div className="wrap" style={{maxWidth: 460, paddingTop: 80}}>
        {!sent ? (
          <>
            <h1 className="serif" style={{fontSize: 40, lineHeight: 1.1, letterSpacing: '-0.022em', margin: '0 0 8px'}}>
              {mode === 'signin' ? <>Welcome <em>back.</em></> : <>Create an <em>account.</em></>}
            </h1>
            <p style={{fontSize: 15, color: 'var(--muted)', margin: '0 0 28px'}}>
              {mode === 'signin' ? "Enter your email — we'll send a sign-in code." : "No password. We'll email you a sign-in code."}
            </p>

            <form onSubmit={submit}>
              {mode === 'signup' && (
                <div className="field">
                  <label className="field-label">Name</label>
                  <input className={'input' + (errors.name ? ' error' : '')} value={name} onChange={(ev) => setName(ev.target.value)} placeholder="Jordan Reeves" />
                  {errors.name && <div className="field-error"><Icon.Alert className="icon-sm" /> {errors.name}</div>}
                </div>
              )}
              <div className="field">
                <label className="field-label">Email</label>
                <input className={'input' + (errors.email ? ' error' : '')} value={email} onChange={(ev) => setEmail(ev.target.value)} placeholder="you@domain.com" autoFocus />
                {errors.email && <div className="field-error"><Icon.Alert className="icon-sm" /> {errors.email}</div>}
              </div>
              {sendErr && <div className="field-error" style={{marginBottom: 12}}><Icon.Alert className="icon-sm" /> Couldn't send the code: {String(sendErr.message || sendErr)}</div>}
              <button type="submit" className="btn btn-primary btn-lg" disabled={submitting} style={{width: '100%', justifyContent: 'center', marginTop: 8}}>
                {submitting ? 'Sending…' : (mode === 'signin' ? 'Send sign-in code' : 'Create account')} <Icon.ArrowRight />
              </button>
            </form>

            <div style={{margin: '24px 0', display: 'flex', alignItems: 'center', gap: 12, color: 'var(--muted)', fontSize: 12, textTransform: 'uppercase', letterSpacing: '0.08em', fontFamily: 'Geist Mono, monospace'}}>
              <div style={{flex: 1, height: 1, background: 'var(--hair)'}} />
              <span>or</span>
              <div style={{flex: 1, height: 1, background: 'var(--hair)'}} />
            </div>

            <div style={{display: 'flex', flexDirection: 'column', gap: 8}}>
              {[['google','Google'],['microsoft','Microsoft'],['github','GitHub'],['apple','Apple']].map(function(pair) {
                return (
                  <button key={pair[0]} type="button" className="btn btn-ghost" style={{width: '100%', justifyContent: 'center'}} onClick={() => goSocial(pair[0])}>
                    Continue with {pair[1]}
                  </button>
                );
              })}
            </div>

            <div style={{marginTop: 32, paddingTop: 20, borderTop: '1px solid var(--hair)', fontSize: 14, color: 'var(--muted)', textAlign: 'center'}}>
              {mode === 'signin'
                ? <>New here? <button type="button" className="btn-bare" style={{color: 'var(--accent)', padding: 0}} onClick={() => onSwitch('signup')}>Create an account</button></>
                : <>Already have one? <button type="button" className="btn-bare" style={{color: 'var(--accent)', padding: 0}} onClick={() => onSwitch('signin')}>Sign in</button></>
              }
            </div>
          </>
        ) : (
          /* ── OTP code entry ── */
          <div>
            <div style={{display: 'inline-flex', width: 44, height: 44, borderRadius: '50%', background: 'rgba(17,17,17,0.07)', color: 'var(--ink)', alignItems: 'center', justifyContent: 'center', marginBottom: 20}}>
              <Icon.Mail />
            </div>
            <h1 className="serif" style={{fontSize: 36, lineHeight: 1.1, letterSpacing: '-0.022em', margin: '0 0 8px'}}>Check your email.</h1>
            <p style={{fontSize: 15, color: 'var(--muted)', lineHeight: 1.6, margin: '0 0 28px'}}>
              We sent a 6-digit code to <strong style={{color: 'var(--ink-2)'}}>{email}</strong>. Enter it below to sign in.
            </p>

            <label className="field-label" style={{display: 'block', marginBottom: 6}}>Sign-in code</label>
            <input
              type="text"
              inputMode="numeric"
              autoComplete="one-time-code"
              maxLength={6}
              placeholder="000000"
              autoFocus
              value={otpCode}
              onChange={(ev) => handleOtpChange(ev.target.value)}
              disabled={verifying}
              style={{
                width: '100%', height: 52, border: '1px solid var(--hair)', borderRadius: 8,
                padding: '0 16px', fontSize: 24, letterSpacing: '0.25em', color: 'var(--ink)',
                background: 'var(--surface)', fontFamily: 'Geist Mono, monospace',
                textAlign: 'center', opacity: verifying ? 0.6 : 1,
                outline: 'none', boxSizing: 'border-box',
              }}
            />

            {verifyErr
              ? <p style={{fontSize: 12, color: 'var(--bad)', marginTop: 8, display: 'flex', alignItems: 'center', gap: 5}}><Icon.Alert className="icon-sm" /> {verifyErr}</p>
              : verifying
                ? <p style={{fontSize: 12, color: 'var(--muted)', marginTop: 8}}>Verifying…</p>
                : <p style={{fontSize: 12, color: 'var(--muted)', marginTop: 8}}>Code auto-submits when 6 digits are entered.</p>
            }

            <div style={{marginTop: 24, display: 'flex', alignItems: 'center', gap: 16}}>
              <button type="button" onClick={handleResend} disabled={resendCooldown > 0 || verifying}
                style={{background: 'none', border: 'none', padding: 0, fontSize: 13, color: resendCooldown > 0 ? 'var(--hair-2)' : 'var(--muted)', cursor: resendCooldown > 0 || verifying ? 'default' : 'pointer', textDecoration: resendCooldown > 0 ? 'none' : 'underline', textUnderlineOffset: 3, fontFamily: 'Geist, sans-serif'}}>
                {resendCooldown > 0 ? 'Resend in ' + resendCooldown + 's' : 'Resend code'}
              </button>
              <span style={{color: 'var(--hair-2)', fontSize: 13}}>·</span>
              <button type="button" onClick={() => { setSent(false); setSendErr(null); setOtpCode(''); setVerifyErr(null); }}
                style={{background: 'none', border: 'none', padding: 0, fontSize: 13, color: 'var(--muted)', cursor: 'pointer', textDecoration: 'underline', textUnderlineOffset: 3, fontFamily: 'Geist, sans-serif'}}>
                Use a different email
              </button>
            </div>
          </div>
        )}
      </div>
      <Footer />
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────
// RUN ERROR — full-page error states
// ─────────────────────────────────────────────────────────────────────
const ERROR_VARIANTS = {
  unreachable: {
    title: 'We couldn\'t reach that page.',
    sub: 'Either the URL doesn\'t resolve, or the server isn\'t responding. Double-check the link and try again.',
    detail: 'Status: connection timeout after 8s',
    retry: true,
  },
  paywall: {
    title: 'That page is behind a login.',
    sub: 'This WorkApp reads only public content. If your homepage requires authentication to view, we can\'t analyze it.',
    detail: 'Status: 401 Unauthorized',
    retry: false,
  },
  blocked: {
    title: 'The site blocked our reader.',
    sub: 'Your site\'s firewall or bot rules rejected our request. Add our IP to your allowlist or run from a different page.',
    detail: 'Status: 403 Forbidden · CDN: cloudflare',
    retry: true,
  },
  thin: {
    title: 'There isn\'t enough on this page to analyze.',
    sub: 'The page loaded, but we couldn\'t find a hero, headline, or any meaningful copy above the fold. Is this a placeholder or coming-soon page?',
    detail: 'Found: 1 hero, 0 headlines, 12 words above fold',
    retry: false,
  },
};

function RunErrorScreen({ variant = 'unreachable', inputs, onRetry, onBack, onDifferentUrl }) {
  const v = ERROR_VARIANTS[variant];
  const domain = inputs?.url ? inputs.url.replace(/^https?:\/\//, '').replace(/\/$/, '') : 'acme.com';

  return (
    <div data-screen-label={'16 Run Error · ' + variant}>
      <div className="wrap" style={{maxWidth: 720, paddingTop: 72}}>
        <div className="section-label" style={{color: '#a13a2e'}}>Run could not complete</div>
        <h1 className="serif" style={{fontSize: 44, lineHeight: 1.1, letterSpacing: '-0.022em', margin: '8px 0 16px'}}>{v.title}</h1>
        <p style={{fontSize: 17, color: 'var(--ink-2)', lineHeight: 1.55, margin: '0 0 32px', maxWidth: 600}}>{v.sub}</p>

        <div className="err-detail">
          <div className="err-detail-row">
            <div className="err-detail-k">Target</div>
            <div className="err-detail-v"><code>{domain}</code></div>
          </div>
          <div className="err-detail-row">
            <div className="err-detail-k">Detail</div>
            <div className="err-detail-v"><code>{v.detail}</code></div>
          </div>
          <div className="err-detail-row">
            <div className="err-detail-k">Time</div>
            <div className="err-detail-v"><code>just now</code></div>
          </div>
        </div>

        <div style={{display: 'flex', gap: 12, marginTop: 32, flexWrap: 'wrap'}}>
          {v.retry && <button className="btn btn-primary" onClick={onRetry}>Try again <Icon.Refresh className="icon-sm" /></button>}
          <button className="btn btn-ghost" onClick={onDifferentUrl}>Use a different URL</button>
          <button className="btn btn-ghost" onClick={onBack}>Back to WorkApp</button>
        </div>

        <div style={{marginTop: 40, padding: '20px 24px', background: 'var(--surface)', border: '1px solid var(--hair)', borderRadius: 'var(--r-md)', fontSize: 13.5, color: 'var(--ink-2)', lineHeight: 1.55}}>
          <div style={{fontFamily: 'Geist Mono, monospace', fontSize: 11, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--muted)', marginBottom: 6}}>Tip</div>
          {variant === 'unreachable' && 'Try the canonical URL with https:// — and make sure your site is live, not a staging redirect.'}
          {variant === 'paywall' && 'Run this on a public marketing page instead of an app subdomain.'}
          {variant === 'blocked' && 'Some firewalls block analyzers by default. Reach out and we can help you allowlist us.'}
          {variant === 'thin' && 'Wait until your homepage has real copy, or run a different WorkApp built for early-stage sites.'}
        </div>
      </div>
      <Footer />
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────
// LEGAL — Privacy and Terms (placeholder static content)
// ─────────────────────────────────────────────────────────────────────
function LegalShell({ title, lead, sections }) {
  return (
    <div data-screen-label="Legal">
      <div className="wrap" style={{maxWidth: 760, paddingTop: 64, paddingBottom: 48}}>
        <div className="section-label">Legal</div>
        <h1 className="serif" style={{fontSize: 48, lineHeight: 1.05, letterSpacing: '-0.025em', margin: '8px 0 18px'}}>{title}</h1>
        <p style={{fontSize: 17, color: 'var(--ink-2)', lineHeight: 1.6, marginBottom: 32}}>{lead}</p>
        {sections.map((s, i) => (
          <section key={i} style={{marginBottom: 28}}>
            <h2 className="serif" style={{fontSize: 22, margin: '0 0 8px'}}>{s.heading}</h2>
            {s.paragraphs.map((p, j) => (
              <p key={j} style={{fontSize: 15.5, color: 'var(--ink-2)', lineHeight: 1.65, margin: '0 0 12px'}}>{p}</p>
            ))}
          </section>
        ))}
        <p style={{fontSize: 13, color: 'var(--muted)', marginTop: 40}}>
          Last updated: {new Date().toLocaleDateString(undefined, { month: 'long', day: 'numeric', year: 'numeric' })}.
          Questions? Email <a href="mailto:legal@workapp.ai" style={{color: 'var(--accent)'}}>legal@workapp.ai</a>.
        </p>
      </div>
      <Footer />
    </div>
  );
}

function PrivacyScreen() {
  return (
    <LegalShell
      title="Privacy Policy"
      lead="This describes what WorkApp.ai collects, how we use it, and your choices. We try to keep it short and human."
      sections={[
        { heading: 'What we collect', paragraphs: [
          'Account: your email (via our login provider), your name if you provide it, and the company you optionally enter in your profile.',
          'Usage: the WorkApps you run, the inputs you submit, the outputs the system returned, and the feedback you give on each result.',
          'Technical: standard request logs (IP, user agent, timestamps) for security and debugging.',
        ]},
        { heading: 'How we use it', paragraphs: [
          'To run the WorkApps you request and show you their outputs.',
          'To improve our methods — your feedback ratings help us measure result quality. Aggregated usage may inform new WorkApps.',
          'To communicate with you about your account or replies to your contact requests. We do not sell your data.',
        ]},
        { heading: 'Sharing', paragraphs: [
          'Public share links you create are accessible by anyone with the link until you revoke them.',
          'We use third-party LLM and infrastructure providers to process runs. They see only what is needed to execute the run.',
        ]},
        { heading: 'Your choices', paragraphs: [
          'You can view, export, or delete your runs from My Runs.',
          'You can delete your account from the Account screen; this removes your profile and your runs.',
        ]},
      ]}
    />
  );
}

function TermsScreen() {
  return (
    <LegalShell
      title="Terms of Service"
      lead="These are the rules for using WorkApp.ai. By using the service you accept them."
      sections={[
        { heading: 'Acceptable use', paragraphs: [
          'Use WorkApps for their stated purpose. Do not submit content you have no right to share, do not attempt to attack the service or circumvent rate limits, and do not use outputs to make decisions where independent professional judgment is required (legal, medical, financial advice).',
        ]},
        { heading: 'Accounts', paragraphs: [
          'You are responsible for activity under your account. Sign in is provided through a third-party identity provider; we do not store your password.',
        ]},
        { heading: 'Content & outputs', paragraphs: [
          'You own the inputs you provide. You receive a non-exclusive right to use the outputs WorkApps return for you. Outputs are produced by automated systems; they may be wrong. Verify before acting on them.',
          'Experts who publish WorkApps own their methodology and framework content; we license it to operate the service.',
        ]},
        { heading: 'Service availability', paragraphs: [
          'The service is provided "as is". We may change or remove WorkApps and features. We will give reasonable notice for breaking changes that affect saved runs.',
        ]},
        { heading: 'Limitation of liability', paragraphs: [
          'To the maximum extent permitted by law, WorkApp.ai is not liable for indirect or consequential damages arising from use of the service.',
        ]},
      ]}
    />
  );
}

Object.assign(window, { MyRunsScreen, AccountScreen, ExpertsDirectoryScreen, BecomeExpertScreen, AboutScreen, AuthScreen, RunErrorScreen, PrivacyScreen, TermsScreen });
