// Pages: Browse / Directory
function BrowsePage({ go, t }) {
  const { WORKFLOWS, OPERATORS, PROBLEMS, TOOLS, INDUSTRIES } = window.HRI_DATA;
  const [tab, setTab] = useState('operators');
  const [q, setQ] = useState('');
  const [filters, setFilters] = useState({ workflow: null, industry: null, tool: null, region: null });
  const density = t.density || 'medium';

  const clearFilters = () => setFilters({ workflow: null, industry: null, tool: null, region: null });
  const activeFilterCount = Object.values(filters).filter(Boolean).length;

  const filteredOperators = OPERATORS.filter(o => {
    if (q && !(o.name + o.bio + o.tools.join(' ')).toLowerCase().includes(q.toLowerCase())) return false;
    if (filters.workflow && !o.workflows.includes(filters.workflow)) return false;
    if (filters.industry && !o.industries.includes(filters.industry)) return false;
    if (filters.tool && !o.tools.includes(filters.tool)) return false;
    return true;
  });

  const filteredProblems = PROBLEMS.filter(p => {
    if (q && !(p.business + p.body).toLowerCase().includes(q.toLowerCase())) return false;
    if (filters.workflow && !p.workflows.includes(filters.workflow)) return false;
    if (filters.industry && p.industry !== filters.industry) return false;
    return true;
  });

  const filteredWorkflows = WORKFLOWS.filter(w => {
    if (q && !(w.name + w.short).toLowerCase().includes(q.toLowerCase())) return false;
    return true;
  });

  return (
    <section style={{ padding: '40px 0 80px' }}>
      <div className="container-wide">
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', flexWrap: 'wrap', gap: 16, marginBottom: 24 }}>
          <div>
            <Kicker>Directory</Kicker>
            <h1 className="h2" style={{ marginTop: 8, fontSize: 'clamp(28px, 3vw, 40px)' }}>Browse the directory</h1>
          </div>
          <div className="mono" style={{ fontSize: 12, color: 'var(--ink-3)', letterSpacing: '0.04em' }}>
            {OPERATORS.length} OPERATORS · {PROBLEMS.length} OPEN PROBLEMS · {WORKFLOWS.length} WORKFLOWS
          </div>
        </div>

        {/* Search bar */}
        <div style={{ display: 'flex', gap: 8, marginBottom: 24 }}>
          <div style={{ flex: 1, position: 'relative' }}>
            <Icon.search style={{ position: 'absolute', left: 14, top: 14, color: 'var(--ink-3)' }} />
            <input className="input" placeholder="Search workflows, operators, tools…" value={q} onChange={e => setQ(e.target.value)} style={{ paddingLeft: 38, padding: '12px 14px 12px 38px' }} />
          </div>
          <DensityToggle density={density} />
        </div>

        {/* Tabs */}
        <div style={{ display: 'flex', borderBottom: '1px solid var(--line)', marginBottom: 24, gap: 4 }}>
          {[['operators', `Operators · ${filteredOperators.length}`], ['problems', `Open problems · ${filteredProblems.length}`], ['workflows', `Workflows · ${filteredWorkflows.length}`]].map(([id, label]) => (
            <button
              key={id}
              onClick={() => setTab(id)}
              style={{
                padding: '12px 18px', background: 'none', border: 0,
                borderBottom: tab === id ? '2px solid var(--accent)' : '2px solid transparent',
                color: tab === id ? 'var(--ink)' : 'var(--ink-3)',
                fontWeight: tab === id ? 500 : 400, fontSize: 14, marginBottom: -1,
              }}
            >{label}</button>
          ))}
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '240px 1fr', gap: 32 }}>
          {/* Filter sidebar */}
          <aside>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
              <span className="kicker">Filters {activeFilterCount > 0 && <span style={{ color: 'var(--accent)' }}>({activeFilterCount})</span>}</span>
              {activeFilterCount > 0 && <button className="btn btn-ghost btn-sm" onClick={clearFilters} style={{ fontSize: 12 }}>Clear</button>}
            </div>
            <FilterGroup label="Workflow" options={WORKFLOWS.map(w => [w.slug, w.name])} value={filters.workflow} onChange={v => setFilters(f => ({...f, workflow: v}))} />
            <FilterGroup label="Industry" options={INDUSTRIES.map(i => [i, i])} value={filters.industry} onChange={v => setFilters(f => ({...f, industry: v}))} max={6} />
            <FilterGroup label="Tool" options={TOOLS.map(t => [t, t])} value={filters.tool} onChange={v => setFilters(f => ({...f, tool: v}))} max={6} />
          </aside>

          {/* Results */}
          <div>
            {tab === 'operators' && (
              <div style={{ display: 'grid', gap: density === 'dense' ? 1 : 12, ...(density === 'dense' ? { background: 'var(--line)', border: '1px solid var(--line)', borderRadius: 'var(--radius)' } : {}) }}>
                {filteredOperators.map(o => density === 'dense' ? <OperatorRow key={o.id} o={o} go={go} /> : <OperatorCard key={o.id} o={o} go={go} density={density} />)}
                {filteredOperators.length === 0 && <EmptyState />}
              </div>
            )}
            {tab === 'problems' && (
              <div style={{ display: 'grid', gap: density === 'dense' ? 1 : 12, ...(density === 'dense' ? { background: 'var(--line)', border: '1px solid var(--line)', borderRadius: 'var(--radius)' } : {}) }}>
                {filteredProblems.map(p => density === 'dense' ? <ProblemRow key={p.id} p={p} go={go} /> : <ProblemCard key={p.id} p={p} go={go} density={density} />)}
                {filteredProblems.length === 0 && <EmptyState />}
              </div>
            )}
            {tab === 'workflows' && (
              <div className="grid grid-2" style={{ gap: 12 }}>
                {filteredWorkflows.map(w => <WorkflowCard key={w.slug} w={w} go={go} />)}
              </div>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}

function FilterGroup({ label, options, value, onChange, max = 8 }) {
  const [expanded, setExpanded] = useState(false);
  const visible = expanded ? options : options.slice(0, max);
  return (
    <div style={{ marginBottom: 24 }}>
      <div className="kicker" style={{ marginBottom: 10 }}>{label}</div>
      <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'grid', gap: 2 }}>
        {visible.map(([id, name]) => (
          <li key={id}>
            <button
              onClick={() => onChange(value === id ? null : id)}
              style={{
                width: '100%', textAlign: 'left', padding: '6px 8px', borderRadius: 4,
                background: value === id ? 'color-mix(in oklab, var(--accent) 12%, transparent)' : 'transparent',
                border: 0, color: value === id ? 'var(--accent-2)' : 'var(--ink-2)',
                fontSize: 13, cursor: 'pointer', lineHeight: 1.3,
                display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8,
                whiteSpace: 'nowrap', overflow: 'hidden',
              }}
              onMouseEnter={e => { if (value !== id) e.currentTarget.style.background = 'var(--bg-1)'; }}
              onMouseLeave={e => { if (value !== id) e.currentTarget.style.background = 'transparent'; }}
            >
              <span style={{ overflow: 'hidden', textOverflow: 'ellipsis' }}>{name}</span>
              {value === id && <Icon.check />}
            </button>
          </li>
        ))}
      </ul>
      {options.length > max && (
        <button className="btn btn-ghost btn-sm" onClick={() => setExpanded(!expanded)} style={{ marginTop: 4, fontSize: 12, color: 'var(--ink-3)' }}>
          {expanded ? 'Less' : `+ ${options.length - max} more`}
        </button>
      )}
    </div>
  );
}

function DensityToggle({ density }) {
  const setD = (d) => window.parent.postMessage({ type: '__edit_mode_set_keys', edits: { density: d } }, '*');
  // Use direct read from html data attribute since tweak panel handles set
  return (
    <div style={{ display: 'flex', border: '1px solid var(--line)', borderRadius: 6, overflow: 'hidden' }}>
      {['sparse', 'medium', 'dense'].map(d => (
        <button key={d} onClick={() => {
          document.getElementById('root').setAttribute('data-density', d);
          window.parent.postMessage({ type: '__edit_mode_set_keys', edits: { density: d } }, '*');
        }} style={{
          padding: '10px 14px', background: density === d ? 'var(--bg-2)' : 'transparent', border: 0,
          color: density === d ? 'var(--ink)' : 'var(--ink-3)', fontSize: 12, textTransform: 'capitalize',
          borderRight: d !== 'dense' ? '1px solid var(--line)' : 0,
        }}>{d}</button>
      ))}
    </div>
  );
}

function OperatorCard({ o, go, density }) {
  const sparse = density === 'sparse';
  return (
    <div className="card" onClick={() => go('operator', o.id)} style={{ cursor: 'pointer', padding: sparse ? 28 : 18, display: 'grid', gridTemplateColumns: 'auto 1fr auto', gap: sparse ? 24 : 18, alignItems: 'flex-start' }}>
      <Avatar initials={o.initials} size={sparse ? 64 : 48} />
      <div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <h3 style={{ fontSize: sparse ? 20 : 17, fontWeight: 500 }}>{o.name}</h3>
          <StatusDot status={o.status} />
        </div>
        <div className="mono" style={{ fontSize: 11, color: 'var(--ink-3)', letterSpacing: '0.04em', marginTop: 4 }}>
          <Icon.pin /> &nbsp;{o.region.toUpperCase()} &nbsp;·&nbsp; {o.languages.join(' · ')} &nbsp;·&nbsp; <Icon.clock /> {o.response.toUpperCase()}
        </div>
        <p style={{ color: 'var(--ink-2)', fontSize: 14, marginTop: 12, marginBottom: 12 }}>{o.bio}</p>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
          {o.workflows.slice(0, 3).map(slug => {
            const w = window.HRI_DATA.WORKFLOWS.find(x => x.slug === slug);
            return <Tag key={slug} accent>{w?.name}</Tag>;
          })}
          {o.tools.slice(0, 3).map(t => <Tag key={t} mono>{t}</Tag>)}
        </div>
      </div>
      <div style={{ textAlign: 'right' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 4, color: 'var(--accent-2)', justifyContent: 'flex-end' }}>
          <Icon.star /> <span style={{ fontWeight: 500 }}>{o.rating}</span>
        </div>
        <div className="mono" style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 6 }}>{o.delivered} DELIVERED</div>
        <div style={{ marginTop: 14, color: 'var(--accent-2)', fontSize: 13 }}>{o.rate}</div>
      </div>
    </div>
  );
}

function OperatorRow({ o, go }) {
  return (
    <div onClick={() => go('operator', o.id)} style={{ background: 'var(--bg)', padding: '12px 18px', display: 'grid', gridTemplateColumns: '32px 1.4fr 2fr 1fr 0.8fr 0.6fr', gap: 16, alignItems: 'center', cursor: 'pointer' }}
      onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-1)'}
      onMouseLeave={e => e.currentTarget.style.background = 'var(--bg)'}>
      <Avatar initials={o.initials} size={32} />
      <div>
        <div style={{ fontWeight: 500, fontSize: 14 }}>{o.name} <StatusDot status={o.status} /></div>
        <div className="mono" style={{ fontSize: 10, color: 'var(--ink-3)' }}>{o.region.toUpperCase()} · {o.languages.join('·')}</div>
      </div>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
        {o.tools.slice(0, 4).map(t => <Tag key={t} mono>{t}</Tag>)}
      </div>
      <div className="mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>{o.workflows.length} workflows</div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 4, color: 'var(--accent-2)', fontSize: 13 }}>
        <Icon.star /> {o.rating} <span style={{ color: 'var(--ink-3)' }}>· {o.delivered}</span>
      </div>
      <div style={{ color: 'var(--accent-2)', fontSize: 13, textAlign: 'right' }}>{o.rate}</div>
    </div>
  );
}

function ProblemCard({ p, go, density }) {
  const sparse = density === 'sparse';
  return (
    <div className="card" onClick={() => go('problem', p.id)} style={{ cursor: 'pointer', padding: sparse ? 28 : 20 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 16 }}>
        <div>
          <h3 style={{ fontSize: 17, fontWeight: 500 }}>{p.business}</h3>
          <div className="mono" style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 4, letterSpacing: '0.04em' }}>
            {p.industry.toUpperCase()} · {p.region.toUpperCase()}
          </div>
        </div>
        <div style={{ textAlign: 'right' }}>
          <span className="mono" style={{ fontSize: 11, color: 'var(--accent)' }}>{p.posted.toUpperCase()}</span>
          <div className="mono" style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 4 }}>{p.contacted} REPLIES</div>
        </div>
      </div>
      <p style={{ color: 'var(--ink-2)', fontSize: 14, marginTop: 14, marginBottom: 14 }}>{p.body}</p>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
        {p.workflows.map(slug => {
          const w = window.HRI_DATA.WORKFLOWS.find(x => x.slug === slug);
          return <Tag key={slug} accent>{w?.name}</Tag>;
        })}
        {p.saas.map(s => <Tag key={s} mono>{s}</Tag>)}
      </div>
      <div style={{ marginTop: 14, fontSize: 12, color: 'var(--ink-3)' }}>Budget · {p.budget}</div>
    </div>
  );
}

function ProblemRow({ p, go }) {
  return (
    <div onClick={() => go('problem', p.id)} style={{ background: 'var(--bg)', padding: '14px 18px', display: 'grid', gridTemplateColumns: '1.2fr 2fr 1fr 0.8fr 0.6fr', gap: 16, alignItems: 'center', cursor: 'pointer' }}
      onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-1)'}
      onMouseLeave={e => e.currentTarget.style.background = 'var(--bg)'}>
      <div>
        <div style={{ fontWeight: 500, fontSize: 14 }}>{p.business}</div>
        <div className="mono" style={{ fontSize: 10, color: 'var(--ink-3)' }}>{p.industry.toUpperCase()} · {p.region.toUpperCase()}</div>
      </div>
      <div style={{ fontSize: 13, color: 'var(--ink-2)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{p.body}</div>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
        {p.workflows.slice(0, 1).map(slug => {
          const w = window.HRI_DATA.WORKFLOWS.find(x => x.slug === slug);
          return <Tag key={slug} accent>{w?.name}</Tag>;
        })}
      </div>
      <div className="mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>{p.contacted} replies</div>
      <div className="mono" style={{ fontSize: 11, color: 'var(--accent)', textAlign: 'right' }}>{p.posted}</div>
    </div>
  );
}

function EmptyState() {
  return (
    <div style={{ padding: 56, textAlign: 'center', border: '1px dashed var(--line)', borderRadius: 'var(--radius)', color: 'var(--ink-3)' }}>
      <div className="mono" style={{ fontSize: 12, letterSpacing: '0.06em' }}>NO RESULTS</div>
      <p style={{ marginTop: 8, fontSize: 14 }}>Try clearing a filter or broadening your search.</p>
    </div>
  );
}

Object.assign(window, { BrowsePage, OperatorCard, ProblemCard });
