// Additional screens: Homepage, Directory, SharedResult, ColdResult, ExpertProfile
//
// T4b: screens load via window.AppData.* in useEffect and render their own
// loading state. No synchronous reads of EXPERT/WORKAPP/EXPERTS/ALL_WORKAPPS.
// Adapter cards already expose `.bg` / `.avatarBg` / `.title` etc. (see
// public/app/data.jsx). Note: API workapp summaries don't yet carry a
// real `cat`/`type`/`audience`/`runs` — the adapter stubs them, so
// category filters degrade gracefully (everything → 'WorkApps' bucket)
// until those fields are populated server-side.

const { useState: useS2, useEffect: useE2 } = React;

// Normalize an expert card (from AppData.listExperts / expertCard) into the
// shape this file's JSX expects for the "experts strip" — fills in role/bg
// fallbacks since the API stub doesn't yet emit role/wapps counts.
function _normExpertCard(e) {
  if (!e) return null;
  return {
    name: e.name,
    slug: e.slug,
    initial: e.initial,
    photo: e.photo,
    bg: e.avatarBg || e.bg,
    avatarBg: e.avatarBg || e.bg,
    role: e.title || e.role || '',
    speciality: e.specialty || e.speciality || '',
    title: e.title || '',
    specialty: e.specialty || '',
    bio: e.bio || '',
    wapps: e.workAppsCount || 0,
    runs: e.totalRuns || '—',
  };
}

// ── HOMEPAGE ─────────────────────────────────────────────────────────
// Homepage shows creator waitlist. The full marketplace view is served at
// /homepage (public — no auth gate), which pre-sets the hash to #/marketplace.
function HomeScreen(props) {
  return <HomeWaitlistScreen onDirectory={props.onDirectory} />;
}

function HomeScreenOriginal({ onWorkApp, onDirectory, onExpert, onExperts, onAbout, onBecomeExpert, onRun, onSeeSample }) {
  const [url, setUrl] = useState_m('');
  const [errors, setErrors] = useState_m({});
  const [touched, setTouched] = useState_m({});
  const [browseCat, setBrowseCat] = useState_m('All');
  const [question, setQuestion] = useState_m('');
  const [questionSubmitted, setQuestionSubmitted] = useState_m(false);
  const [questionSaved, setQuestionSaved] = useState_m(false);
  const [workapps, setWorkapps] = useState_m(null);
  const [experts, setExperts] = useState_m(null);
  const [featuredInputs, setFeaturedInputs] = useState_m(null);

  useEffect_m(() => {
    let cancelled = false;
    Promise.all([
      window.AppData.listWorkapps().catch(() => []),
      window.AppData.listExperts().catch(() => []),
    ]).then(([wapps, exps]) => {
      if (cancelled) return;
      setWorkapps(wapps || []);
      setExperts((exps || []).map(_normExpertCard).filter(Boolean));
    });
    return () => { cancelled = true; };
  }, []);

  useEffect_m(function() {
    if (!workapps || workapps.length === 0) return;
    var f = workapps.find(function(w) { return w && w.isMain; }) || workapps[0];
    if (!f || !f.slug) return;
    var cancelled = false;
    window.AppData.getWorkapp(f.slug).then(function(d) {
      if (!cancelled) setFeaturedInputs(d.inputs || []);
    }).catch(function() {});
    return function() { cancelled = true; };
  }, [workapps]);

  // Derive categories from actual loaded workapps — no hardcoded list.
  const browseCats = ['All'].concat(
    Array.from(new Set((workapps || []).map(function(w) { return w && w.cat; }).filter(Boolean)))
      .filter(function(c) { return c !== 'WorkApps'; })
  );
  const matchQuestion = (w, q) => {
    const terms = q.toLowerCase().split(/\s+/).map(t => t.replace(/[^a-z0-9]/g, '')).filter(t => t.length > 2);
    if (!terms.length) return true;
    const haystack = [w.title, w.cat, w.type, w.audience, w.expert].join(' ').toLowerCase();
    return terms.some(t => haystack.includes(t));
  };
  const allWorkapps = workapps || [];
  const questionMatches = question.trim()
    ? allWorkapps.filter(w => matchQuestion(w, question.trim()))
    : [];
  const browseBase = questionSubmitted && question.trim()
    ? questionMatches
    : allWorkapps.filter(w => browseCat === 'All' || w.cat === browseCat);
  const browseWorkApps = browseBase.slice(0, 6);
  // Featured workapp + expert for the hero card — derived from API data,
  // not hardcoded. Falls back to neutral values until data loads.
  const featured = (workapps || []).find(function(w) { return w && w.isMain; }) || (workapps || [])[0] || null;
  const featuredTitle = featured ? window.AppData.splitItalic(featured.title || '') : { title: '', italic: '' };
  const featuredExpert = (experts && experts.find(function(e) { return featured && e.name === (featured.expert || ''); }))
    || (experts && experts[0])
    || { name: '', initial: '?', avatarBg: 'linear-gradient(135deg, #d4a373, #a0522d)' };

  var firstInput = (featuredInputs && featuredInputs[0]) || { name: 'url', label: 'Your homepage URL', type: 'url', description: '' };
  var isUrlField = firstInput.type === 'url' || /url/i.test(firstInput.name);

  const submit = (ev) => {
    ev.preventDefault();
    setTouched({ url: true });
    const trimmed = url.trim();
    const errs = {};
    if (!trimmed) errs.url = 'Please enter ' + (firstInput.label || 'a value').toLowerCase() + '.';
    else if (isUrlField && !/^(https?:\/\/)?([\w-]+\.)+[\w-]+(\/.*)?$/i.test(trimmed)) {
      errs.url = "That doesn't look like a URL. Try acme.com.";
    }
    setErrors(errs);
    if (Object.keys(errs).length === 0) {
      var finalValue = trimmed;
      if (isUrlField && !/^https?:\/\//.test(finalValue)) finalValue = 'https://' + finalValue;
      const featured = (workapps || []).find(function (w) { return w && w.isMain; }) || (workapps || [])[0];
      var payload = { slug: featured && featured.slug };
      payload[firstInput.name] = finalValue;
      onRun && onRun(payload);
    }
  };

  const submitQuestion = (ev) => {
    ev.preventDefault();
    if (!question.trim()) return;
    setQuestionSubmitted(true);
    setQuestionSaved(false);
    setBrowseCat('All');
  };

  return (
    <div data-screen-label="00 Homepage">
      <div className="wrap">
        <div className="home-hero home-hero-single">
          <h1 className="serif">Expert methods you can <em>run.</em></h1>
          <p>WorkApp.ai turns expert frameworks into focused diagnostics for positioning, SEO, AI visibility, and growth. Run one on your company and get a verdict, evidence, what to fix first, and what to ignore.</p>

          <h2 className="home-feature-heading">Run one in 60 seconds</h2>
          <form className="home-feature-row" onSubmit={submit}>
            <div className="home-feature-meta">
              <h3 className="serif" style={{margin: 0, fontSize: 24, fontWeight: 500, letterSpacing: '-0.016em'}}>
                {featuredTitle.title ? (
                  <>{featuredTitle.title.replace(featuredTitle.italic || '', '').trim()} {featuredTitle.italic ? <em>{featuredTitle.italic}</em> : null}</>
                ) : 'Featured WorkApp'}
              </h3>
              <div className="home-feature-byline">
                <ExpertAvatar person={featuredExpert} className="mini-avatar" style={{background: featuredExpert.avatarBg}} />
                <span>A method by <b>{featuredExpert.name || 'an expert'}</b></span>
              </div>
              <div className="home-output-preview" aria-label="Featured WorkApp output preview">
                <p><b>You’ll get:</b> verdict, evidence from your page, what to fix first, and what to ignore.</p>
              </div>
            </div>

            <div className="home-feature-input">
              <label className="field-label" htmlFor="hurl">{firstInput.label || 'Your homepage URL'}</label>
              <div className="home-feature-action">
                <input
                  id="hurl"
                  className={'input input-lg' + (errors.url && touched.url ? ' error' : '')}
                  placeholder={isUrlField ? 'acme.com' : (firstInput.description || firstInput.label || '')}
                  value={url}
                  onChange={(ev) => { setUrl(ev.target.value); if (errors.url) setErrors({}); }}
                  onBlur={() => setTouched({...touched, url: true})}
                />
                <button type="submit" className="btn btn-primary btn-lg home-feature-cta">
                  Get my verdict <Icon.ArrowRight />
                </button>
              </div>
              <div className="home-feature-trust">
                <span><Icon.Clock className="icon-sm" /> ~60 seconds · No signup · No credit card</span>
              </div>
              {errors.url && touched.url && (
                <div className="field-error"><Icon.Alert className="icon-sm" /> {errors.url}</div>
              )}
            </div>
          </form>

          <div className="home-promise-strip">
            <span>Every WorkApp returns:</span>
            <b>Verdict</b>
            <span className="promise-dot"></span>
            <b>Evidence</b>
            <span className="promise-dot"></span>
            <b>Fix first</b>
            <span className="promise-dot"></span>
            <b>Ignore</b>
          </div>
        </div>

        <div className="home-section home-browse-section">
          <div className="header">
            <div>
              <h2>Pick the question you need answered</h2>
              <p>Choose a question, run the method, and get a company-specific answer.</p>
            </div>
          </div>
          <div className="home-browse-controls" aria-label="Filter WorkApps by category">
            <span>Category</span>
            {browseCats.map(c => (
              <button
                className={`filter-chip cat-${c.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')} ${browseCat === c ? 'active' : ''}`}
                key={c}
                onClick={() => setBrowseCat(c)}
              >
                {c}
              </button>
            ))}
          </div>
          {browseCat !== 'All' && (
            <div className="home-active-filter" aria-live="polite">
              <span>Showing {browseWorkApps.length} in {browseCat}</span>
              <button type="button" className="btn-bare btn-sm" onClick={() => setBrowseCat('All')}>
                Clear <Icon.X className="icon-sm" />
              </button>
            </div>
          )}
          <div className="featured-grid">
            {browseWorkApps.map((w, i) => (
              <WorkAppCard key={i} wapp={w} onClick={() => onWorkApp(w)} />
            ))}
          </div>
          {browseWorkApps.length === 0 && (
            <div className="home-browse-empty">
              <p>No WorkApps in this category yet.</p>
              <button className="btn btn-ghost btn-sm" onClick={() => setBrowseCat('All')}>Show all</button>
            </div>
          )}
          <form className="question-search-card" onSubmit={submitQuestion}>
            <div>
              <h3>Or ask your own question.</h3>
              <p>Ask in your own words. We’ll find the closest WorkApp, or save the question if none exists yet.</p>
            </div>
            <div className="question-search-row">
              <input
                className="input"
                placeholder="e.g. Should we hire an SEO agency or fix content ourselves?"
                value={question}
                onChange={(ev) => { setQuestion(ev.target.value); setQuestionSubmitted(false); setQuestionSaved(false); }}
              />
              <button className="btn btn-primary" type="submit">Find a WorkApp <Icon.ArrowRight className="icon-sm" /></button>
            </div>
            {questionSubmitted && question.trim() && questionMatches.length > 0 && (
              <div className="question-search-state">
                Showing {Math.min(questionMatches.length, 6)} closest {questionMatches.length === 1 ? 'WorkApp' : 'WorkApps'} for “{question.trim()}”.
                <button type="button" className="btn-bare btn-sm" onClick={() => { setQuestion(''); setQuestionSubmitted(false); }}>Clear</button>
              </div>
            )}
            {questionSubmitted && question.trim() && questionMatches.length === 0 && (
              <div className="question-search-state question-search-empty">
                <span>No matching WorkApp yet.</span>
                {questionSaved ? (
                  <b>Question saved. We’ll notify you when an expert publishes a match.</b>
                ) : (
                  <button type="button" className="btn btn-ghost btn-sm" onClick={() => setQuestionSaved(true)}>Save question</button>
                )}
              </div>
            )}
            <div className="question-search-footer">
              Prefer to browse the full catalog?
              <button type="button" className="btn-bare btn-sm" onClick={onDirectory}>View all WorkApps <Icon.ArrowRight className="icon-sm" /></button>
            </div>
          </form>
        </div>

        <section className="home-alt-trust home-main-trust">
          <div>
            <h2>Methods by people who’ve earned the right to publish them.</h2>
            <p>Every WorkApp is based on a specific expert’s framework, not a generic prompt. Browse the people behind the methods and run their thinking on your company.</p>
            <button className="btn btn-ghost btn-sm home-trust-cta" onClick={onExperts}>
              View all experts <Icon.ArrowRight className="icon-sm" />
            </button>
          </div>
          <div className="home-alt-experts">
            {(experts || []).map((e, i) => (
              <a className="home-alt-expert" key={i} href={e.slug ? '#/experts/' + e.slug : '#/experts'} onClick={(ev) => { ev.preventDefault(); onExpert(e); }}>
                <ExpertAvatar person={e} className="mini-avatar" style={{background: e.bg}} />
                <div>
                  <b>{e.name}</b>
                  <span>{e.role}{e.wapps ? ' · ' + e.wapps + ' ' + (e.wapps === 1 ? 'WorkApp' : 'WorkApps') : ''}</span>
                </div>
              </a>
            ))}
          </div>
        </section>

        <div className="publish-cta">
          <div>
            <h3>Are you the expert with the framework?</h3>
            <p>Turn your method into a runnable WorkApp your audience can use. We onboard experts directly and help shape the first WorkApps with you.</p>
          </div>
          <div style={{textAlign: 'right'}}>
            <button type="button" className="btn btn-primary btn-lg" onClick={onBecomeExpert}>
              Publish a WorkApp <Icon.ArrowRight />
            </button>
          </div>
        </div>
      </div>
      <Footer />
    </div>
  );
}

// ── HOMEPAGE ALT — diagnostic-first variant ─────────────────────────
function HomeAltScreen({ onWorkApp, onDirectory, onExpert, onRun, onSeeSample }) {
  const [url, setUrl] = useState_m('');
  const [errors, setErrors] = useState_m({});
  const [touched, setTouched] = useState_m({});
  const [workapps, setWorkapps] = useState_m(null);
  const [experts, setExperts] = useState_m(null);
  const [featuredInputs, setFeaturedInputs] = useState_m(null);

  useEffect_m(() => {
    let cancelled = false;
    Promise.all([
      window.AppData.listWorkapps().catch(() => []),
      window.AppData.listExperts().catch(() => []),
    ]).then(([wapps, exps]) => {
      if (cancelled) return;
      setWorkapps(wapps || []);
      setExperts((exps || []).map(_normExpertCard).filter(Boolean));
    });
    return () => { cancelled = true; };
  }, []);

  useEffect_m(function() {
    if (!workapps || workapps.length === 0) return;
    var f = workapps.find(function(w) { return w && w.isMain; }) || workapps[0];
    if (!f || !f.slug) return;
    var cancelled = false;
    window.AppData.getWorkapp(f.slug).then(function(d) {
      if (!cancelled) setFeaturedInputs(d.inputs || []);
    }).catch(function() {});
    return function() { cancelled = true; };
  }, [workapps]);

  const browseWorkApps = (workapps || []).filter(w => !w.isMain).slice(0, 4);
  const featured = (workapps || []).find(function(w) { return w && w.isMain; }) || (workapps || [])[0] || null;
  const featuredTitle = featured ? window.AppData.splitItalic(featured.title || '') : { title: '', italic: '' };
  const featuredExpert = (experts && experts.find(function(e) { return featured && e.name === (featured.expert || ''); }))
    || (experts && experts[0])
    || { name: '', initial: '?', avatarBg: 'linear-gradient(135deg, #d4a373, #a0522d)' };

  var altFirstInput = (featuredInputs && featuredInputs[0]) || { name: 'url', label: 'Homepage URL', type: 'url', description: '' };
  var altIsUrlField = altFirstInput.type === 'url' || /url/i.test(altFirstInput.name);

  const submit = (ev) => {
    ev.preventDefault();
    setTouched({ url: true });
    const trimmed = url.trim();
    const errs = {};
    if (!trimmed) errs.url = 'Please enter ' + (altFirstInput.label || 'a value').toLowerCase() + '.';
    else if (altIsUrlField && !/^(https?:\/\/)?([\w-]+\.)+[\w-]+(\/.*)?$/i.test(trimmed)) {
      errs.url = "That doesn't look like a URL. Try acme.com.";
    }
    setErrors(errs);
    if (Object.keys(errs).length === 0) {
      var finalValue = trimmed;
      if (altIsUrlField && !/^https?:\/\//.test(finalValue)) finalValue = 'https://' + finalValue;
      var payload = { slug: featured && featured.slug };
      payload[altFirstInput.name] = finalValue;
      onRun && onRun(payload);
    }
  };

  return (
    <div data-screen-label="00 Homepage Alt">
      <div className="wrap">
        <section className="home-alt-hero">
          <div className="home-alt-kicker">Homepage clarity diagnostic</div>
          <h1 className="serif">Get an expert verdict on your homepage in 60 seconds.</h1>
          <p className="home-alt-sub">
            {featuredExpert.name ? `Run ${featuredExpert.name}'s method on your homepage.` : 'Run an expert method on your homepage.'} You'll get a clear verdict,
            the evidence behind it, what to fix first, and what to ignore.
          </p>

          <form className="home-alt-runner" onSubmit={submit}>
            <div className="home-alt-runner-head">
              <ExpertAvatar person={featuredExpert} className="mini-avatar home-alt-expert-avatar" style={{background: featuredExpert.avatarBg}} />
              <div>
                <div className="home-alt-runner-title">
                  {featuredTitle.title || 'Run a WorkApp'}
                  {featuredTitle.italic ? <> — <em>{featuredTitle.italic}</em></> : null}
                </div>
                <div className="home-alt-runner-meta">
                  Method by {featuredExpert.name || 'expert'}{featuredExpert.title ? ` · ${featuredExpert.title}` : ''}
                </div>
              </div>
            </div>
            <label className="field-label" htmlFor="halt-url">{altFirstInput.label || 'Homepage URL'}</label>
            <div className="home-alt-action">
              <input
                id="halt-url"
                className={'input input-lg' + (errors.url && touched.url ? ' error' : '')}
                placeholder={altIsUrlField ? 'acme.com' : (altFirstInput.description || altFirstInput.label || '')}
                value={url}
                onChange={(ev) => { setUrl(ev.target.value); if (errors.url) setErrors({}); }}
                onBlur={() => setTouched({...touched, url: true})}
              />
              <button type="submit" className="btn btn-primary btn-lg">
                Get my verdict <Icon.ArrowRight />
              </button>
            </div>
            {errors.url && touched.url && (
              <div className="field-error"><Icon.Alert className="icon-sm" /> {errors.url}</div>
            )}
            <div className="home-alt-foot">
              <span><Icon.Clock className="icon-sm" /> ~60 seconds</span>
              <span>No signup</span>
              <span>No credit card</span>
            </div>
          </form>
        </section>

        <section className="home-alt-output">
          <div className="home-alt-section-head">
            <div>
              <div className="section-label">Every run returns</div>
              <h2>One page of judgment, not a generic audit.</h2>
            </div>
          </div>
          <div className="home-alt-output-grid">
            <div className="home-alt-output-row">
              <div className="home-alt-output-k">Verdict</div>
              <div className="home-alt-output-v">Clear enough to understand. Not urgent enough to act.</div>
            </div>
            <div className="home-alt-output-row">
              <div className="home-alt-output-k">Evidence</div>
              <div className="home-alt-output-v">The exact page signals the method used.</div>
            </div>
            <div className="home-alt-output-row home-alt-output-accent">
              <div className="home-alt-output-k">Fix first</div>
              <div className="home-alt-output-v">The highest-leverage change to make next.</div>
            </div>
            <div className="home-alt-output-row">
              <div className="home-alt-output-k">Ignore</div>
              <div className="home-alt-output-v">Distractions that are not the bottleneck.</div>
            </div>
          </div>
        </section>

        <section className="home-alt-browse">
          <div className="home-alt-section-head">
            <div>
              <div className="section-label">Not working on homepage clarity?</div>
              <h2>Browse other expert WorkApps.</h2>
            </div>
            <button className="btn btn-ghost btn-sm" onClick={onDirectory}>View all <Icon.ArrowRight className="icon-sm" /></button>
          </div>
          <div className="featured-grid home-alt-card-list">
            {browseWorkApps.map((w, i) => (
              <WorkAppCard key={i} wapp={w} onClick={() => onWorkApp(w)} />
            ))}
          </div>
        </section>

        <section className="home-alt-trust">
          <div>
            <div className="section-label">Published by practitioners</div>
            <h2>Methods by people who've earned the right to publish them.</h2>
          </div>
          <div className="home-alt-experts">
            {(experts || []).map((e, i) => (
              <a className="home-alt-expert" key={i} href={e.slug ? '#/experts/' + e.slug : '#/experts'} onClick={(ev) => { ev.preventDefault(); onExpert(e); }}>
                <ExpertAvatar person={e} className="mini-avatar" style={{background: e.bg}} />
                <div>
                  <b>{e.name}</b>
                  <span>{e.role}{e.wapps ? ' · ' + e.wapps + ' ' + (e.wapps === 1 ? 'WorkApp' : 'WorkApps') : ''}</span>
                </div>
              </a>
            ))}
          </div>
        </section>
      </div>
      <Footer />
    </div>
  );
}

// ── DIRECTORY ────────────────────────────────────────────────────────
function DirectoryScreen({ onWorkApp }) {
  const [search, setSearch] = useS2('');
  const [cat, setCat] = useS2('All');
  const [sort, setSort] = useS2('Featured');
  const [savedQuestion, setSavedQuestion] = useS2(false);
  const [workapps, setWorkapps] = useS2(null);

  useE2(() => {
    let cancelled = false;
    window.AppData.listWorkapps()
      .then((d) => { if (!cancelled) setWorkapps(d || []); })
      .catch(() => { if (!cancelled) setWorkapps([]); });
    return () => { cancelled = true; };
  }, []);

  const allWorkapps = workapps || [];
  // Derive categories from actual workapp data — no hardcoded list.
  const uniqueCats = Array.from(new Set(allWorkapps.map(function(w) { return w && w.cat; }).filter(Boolean)))
    .filter(function(c) { return c !== 'WorkApps'; });
  const cats = ['All'].concat(uniqueCats);
  const counts = cats.reduce((acc, c) => {
    acc[c] = c === 'All' ? allWorkapps.length : allWorkapps.filter(w => w.cat === c).length;
    return acc;
  }, {});
  const clearFilters = () => {
    setSearch('');
    setCat('All');
    setSort('Featured');
    setSavedQuestion(false);
  };
  let filtered = allWorkapps.filter(w => {
    if (cat !== 'All' && w.cat !== cat) return false;
    if (search === '') return true;
    const needle = search.toLowerCase();
    const haystack = [w.title, w.expert, w.cat, w.type, w.audience]
      .filter(Boolean)
      .join(' ')
      .toLowerCase();
    return haystack.includes(needle);
  });
  if (sort === 'Popular') filtered = [...filtered].sort((a, b) => b.runs - a.runs);
  if (sort === 'Fastest') filtered = [...filtered].sort((a, b) => parseInt(String(a.time).replace(/\D/g, ''), 10) - parseInt(String(b.time).replace(/\D/g, ''), 10));
  if (sort === 'A-Z') filtered = [...filtered].sort((a, b) => (a.title || '').localeCompare(b.title || ''));

  return (
    <div className="dir-page" data-screen-label="05 Directory">
      <div className="wrap">
        <div className="dir-head">
          <h1 className="serif">All WorkApps</h1>
          <p>Search by the question you need answered. If no WorkApp answers it yet, we’ll save the question and notify you when one does. {allWorkapps.length} live.</p>
        </div>

        <div className="dir-question-search">
          <div>
            <h2>What are you trying to decide?</h2>
          </div>
          <div className="dir-search">
            <Icon.Sparkle className="icon" style={{color: 'var(--muted)'}} />
            <input aria-label="Search WorkApps" placeholder="e.g. Should we hire an SEO agency or fix content ourselves?" value={search} onChange={(e) => { setSearch(e.target.value); setSavedQuestion(false); }} />
            {search && <button className="btn-bare btn-sm" aria-label="Clear search" onClick={() => setSearch('')}><Icon.X /></button>}
          </div>
        </div>

        <div className="dir-filters">
          <span style={{fontSize: 12, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.06em', marginRight: 4, fontFamily: 'Geist Mono, monospace'}}>Category</span>
          {cats.map(c => (
            <button className={`filter-chip cat-${c.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')} ${cat === c ? 'active' : ''}`} key={c} onClick={() => setCat(c)}>
              {c} <span>{counts[c]}</span>
            </button>
          ))}
        </div>

        <div className="dir-meta">
          <div>
            <span>{filtered.length === 0 ? 'No matching WorkApps' : `${filtered.length} ${filtered.length === 1 ? 'WorkApp' : 'WorkApps'}`}{cat !== 'All' ? ` in ${cat}` : ''}</span>
            {(search || cat !== 'All' || sort !== 'Featured') && (
              <div className="active-filters" aria-label="Applied filters">
                {search && <button className="active-filter" onClick={() => setSearch('')}>Search: {search} <Icon.X className="icon-sm" /></button>}
                {cat !== 'All' && <button className="active-filter" onClick={() => setCat('All')}>Category: {cat} <Icon.X className="icon-sm" /></button>}
                {sort !== 'Featured' && <button className="active-filter" onClick={() => setSort('Featured')}>Sort: {sort} <Icon.X className="icon-sm" /></button>}
                <button className="btn-bare btn-sm" onClick={clearFilters}>Clear all</button>
              </div>
            )}
          </div>
          <label className="dir-sort">
            <span>Sort</span>
            <select value={sort} onChange={(ev) => setSort(ev.target.value)}>
              <option>Featured</option>
              <option>Popular</option>
              <option>Fastest</option>
              <option>A-Z</option>
            </select>
          </label>
        </div>

        <div className="dir-grid">
          {filtered.map((w, i) => (
            <WorkAppCard key={i} wapp={w} onClick={() => onWorkApp(w)} />
          ))}
        </div>

        {filtered.length === 0 && (
          <div className="dir-empty">
            <h3>No matching WorkApp yet.</h3>
            <p>We can save this question and notify you when an expert publishes a WorkApp that answers it.</p>
            <div className="dir-empty-nearby">
              <div className="section-label">Closest available</div>
              {allWorkapps.slice(0, 3).map((w, i) => (
                <button key={i} className="nearby-match" onClick={() => onWorkApp(w)}>
                  <span>{w.title}</span>
                  <Icon.ArrowRight className="icon-sm" />
                </button>
              ))}
            </div>
            <div>
              {savedQuestion ? (
                <span className="inline-status"><Icon.CheckSm className="icon-sm" /> Question saved for the V1 waitlist.</span>
              ) : (
                <button className="btn btn-primary btn-sm" onClick={() => setSavedQuestion(true)}>Save question</button>
              )}
              <button className="btn btn-ghost btn-sm" onClick={clearFilters}>Clear filters</button>
              <button className="btn btn-ghost btn-sm" onClick={() => allWorkapps[0] && onWorkApp(allWorkapps[0])}>Run featured WorkApp</button>
            </div>
          </div>
        )}
      </div>
      <Footer />
    </div>
  );
}

// ── EXPERT PROFILE ───────────────────────────────────────────────────
function ExpertProfileScreen({ expert, expertSlug, onWorkApp, onRequireAuth, signedIn }) {
  const [loaded, setLoaded] = useS2(null);            // { expert, workapps } from API
  const [loadError, setLoadError] = useS2(null);

  useE2(() => {
    if (!expertSlug) return;
    let cancelled = false;
    window.AppData.getExpert(expertSlug)
      .then((d) => { if (!cancelled) setLoaded(d); })
      .catch((err) => {
        if (cancelled) return;
        if (err && err.status === 401) { window.AppData.redirectToLogin(); return; }
        setLoadError(err);
      });
    return () => { cancelled = true; };
  }, [expertSlug]);

  // Compose the expert object: prefer the explicit `expert` prop (prototype's
  // demo path, e.g. clicked from the experts strip), fall back to the API-
  // loaded expert. No `window.EXPERT` reads — those globals are null after T3.
  const base = (expert || (loaded && loaded.expert) || null);
  if (!base && !loadError && expertSlug) {
    return <div className="loading" style={{padding: 40}}>Loading…</div>;
  }
  if (!base) {
    return <div className="loading" style={{padding: 40}}>Couldn't load expert profile.</div>;
  }
  const e = { ...base };
  if (typeof EXPERT_PHOTOS !== 'undefined' && EXPERT_PHOTOS[e.name]) e.photo = EXPERT_PHOTOS[e.name];
  const title = e.title || e.role || '';
  const specialty = e.specialty || e.speciality || '';
  const firstName = (e.name || '').split(' ')[0] || '';
  const bio = e.bioLong || (expert && expert.bio) || e.bio || (firstName
    ? `${firstName} publishes practical WorkApps for early GTM teams that need expert judgment without a long consulting process. Each method turns their framework into a focused decision flow with a verdict, evidence, and what to fix first.`
    : '');
  const tags = Array.isArray(e.tags) ? e.tags : [];
  const linkedinUrl = e.linkedinUrl || '';
  const websiteUrl = e.websiteUrl || '';
  const servicePackages = Array.isArray(e.servicePackages) ? e.servicePackages : [];
  const stats = (loaded && loaded.stats) || null;
  const myWapps = (loaded && loaded.workapps ? loaded.workapps : []);
  return (
    <div className="profile-page" data-screen-label="08 Expert Profile">
      <div className="wrap">
          <div className="profile-header">
          <ExpertAvatar person={e} className="profile-avatar" style={{background: 'linear-gradient(135deg, #d4a373, #a0522d)'}} />
          <div>
            <div className="profile-name-row">
              <h1 className="profile-name serif">{e.name}</h1>
              <span className="verified-badge">Verified</span>
            </div>
            <div className="profile-title">{title}{specialty ? ' · ' + specialty : ''}</div>
            {tags.length > 0 && (
              <div className="profile-tags">
                {tags.map((t, i) => <span key={i} className="tag">{t}</span>)}
              </div>
            )}
            <p style={{fontSize: 16, color: 'var(--ink-2)', lineHeight: 1.65, margin: '0 0 22px', maxWidth: '62ch'}}>
              {bio}
            </p>
            <div style={{display: 'flex', gap: 8, flexWrap: 'wrap'}}>
              <button className="btn btn-primary" data-ph-cta="contact_expert" onClick={() => {
                if (!signedIn) { onRequireAuth('Sign in to contact ' + e.name); return; }
                const subject = encodeURIComponent('Inquiry from WorkApp.ai about ' + e.name + "'s expertise");
                const body = encodeURIComponent("Hi " + firstName + ",\n\nI tried one of your WorkApps and would like to discuss working together.\n\n— Sent via WorkApp.ai");
                window.location.href = 'mailto:experts@workapp.ai?subject=' + subject + '&body=' + body;
              }}>Contact {firstName}</button>
              {linkedinUrl && (
                <a className="btn btn-ghost" href={linkedinUrl} target="_blank" rel="noopener noreferrer">
                  <Icon.LinkedIn /> LinkedIn <Icon.ExternalLink />
                </a>
              )}
              {websiteUrl && (
                <a className="btn btn-ghost" href={websiteUrl} target="_blank" rel="noopener noreferrer">
                  {websiteUrl.replace(/^https?:\/\//, '').replace(/\/$/, '')} <Icon.ExternalLink />
                </a>
              )}
            </div>
            <div className="profile-stats">
              <div className="profile-stat"><div className="num">{myWapps.length}</div><div className="lbl">WorkApps</div></div>
              {stats && (
                <>
                  <div className="profile-stat"><div className="num">{stats.totalRuns}</div><div className="lbl">Total runs</div></div>
                  <div className="profile-stat"><div className="num">{stats.resultShares}</div><div className="lbl">Result shares</div></div>
                  {stats.avgRating !== null && (
                    <div className="profile-stat"><div className="num">{stats.avgRating.toFixed(1)}</div><div className="lbl">Avg rating</div></div>
                  )}
                </>
              )}
            </div>
          </div>
        </div>

        <div className="home-section" style={{borderBottom: '1px solid var(--hair)'}}>
          <div className="header">
            <div>
              <div className="section-label">Published</div>
              <h2>WorkApps by {e.name}</h2>
            </div>
          </div>
          <div className="related-grid">
            {myWapps.map((w, i) => (
              <WorkAppCard key={i} wapp={w} variant="compact" onClick={() => onWorkApp(w)} />
            ))}
          </div>
        </div>

        {servicePackages.length > 0 && (
          <div className="home-section" style={{borderBottom: 0, paddingTop: 48}}>
            <div className="header">
              <div>
                <div className="section-label">Service packages</div>
                <h2>Want {firstName} to do the work?</h2>
                <p style={{color: 'var(--muted)', fontSize: 14.5, marginTop: 6, maxWidth: '54ch'}}>
                  WorkApps catch the obvious gaps in 60 seconds. For deeper engagements, {firstName} takes on a small number of clients per quarter.
                </p>
              </div>
            </div>
            <div className="package-grid">
              {servicePackages.map((p, i) => (
                <div key={i} className={'package-card' + (p.badge ? ' package-card-feat' : '')}>
                  <div className="package-head">
                    <h4>{p.name}</h4>
                    <span className={'tag' + (p.badge ? ' tag-accent' : '')}>{p.badge || p.duration}</span>
                  </div>
                  <p>{p.body}</p>
                  <ul className="package-list">
                    {(p.items || []).map((it, j) => <li key={j}>{it}</li>)}
                  </ul>
                  <div className="package-foot">
                    <div className="package-price">{p.price} <small>{p.priceKind === 'recurring' ? '/ month' : (p.badge ? p.duration : 'fixed')}</small></div>
                    <button
                      className={'btn btn-sm ' + (p.badge ? 'btn-primary' : 'btn-ink')}
                      onClick={() => {
                        if (!signedIn) { onRequireAuth('Sign in to inquire about ' + p.name); return; }
                        const subject = encodeURIComponent('Inquiry: ' + p.name + ' with ' + e.name);
                        const body = encodeURIComponent("Hi " + firstName + ",\n\nI'm interested in the " + p.name + " package.\n\n— Sent via WorkApp.ai");
                        window.location.href = 'mailto:experts@workapp.ai?subject=' + subject + '&body=' + body;
                      }}
                    >Inquire</button>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
      <Footer />
    </div>
  );
}

Object.assign(window, { HomeScreen, HomeAltScreen, DirectoryScreen, ExpertProfileScreen });
