// Problem detail (public listing) + Search results (filters as removable chips)
const { useState: useStateX } = React;

function ProblemDetailPage({ go, pid }) {
  const { PROBLEMS, WORKFLOWS } = window.HRI_DATA;
  const p = PROBLEMS.find(x => x.id === pid) || PROBLEMS[0];
  const [contactOpen, setContactOpen] = useStateX(false);

  return (
    <>
      <section style={{ padding: '40px 0 32px' }}>
        <div className="container">
          <button className="btn btn-ghost btn-sm" onClick={() => go('browse')} style={{ marginBottom: 24, fontSize: 12, color: 'var(--ink-3)' }}>
            ← Back to directory
          </button>

          <div style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: 32, alignItems: 'flex-start' }}>
            <div>
              <Kicker>Open problem · posted {p.posted}</Kicker>
              <h1 className="h2" style={{ fontSize: 38, marginTop: 12, lineHeight: 1.1 }}>
                {p.business}
              </h1>
              <div className="mono" style={{ fontSize: 12, color: 'var(--ink-3)', letterSpacing: '0.05em', marginTop: 12, textTransform: 'uppercase' }}>
                <Icon.pin /> {p.region} &nbsp;·&nbsp; {p.industry} &nbsp;·&nbsp; <Icon.clock /> {p.contacted} OPERATORS REACHED OUT
              </div>
            </div>
            <button className="btn btn-primary btn-lg" onClick={() => setContactOpen(true)}>
              Reach out to this company <Icon.arrow />
            </button>
          </div>
        </div>
      </section>

      <section className="section-tight">
        <div className="container" style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 48 }}>
          <div>
            <div className="kicker" style={{ marginBottom: 16 }}>The problem, in their words</div>
            <p style={{ fontFamily: 'var(--font-serif)', fontSize: 22, lineHeight: 1.5, color: 'var(--ink)', fontStyle: 'italic', borderLeft: '3px solid var(--accent)', paddingLeft: 20, margin: 0 }}>
              "{p.body}"
            </p>

            <div style={{ marginTop: 48 }}>
              <div className="kicker" style={{ marginBottom: 12 }}>Workflows wanted</div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                {p.workflows.map(slug => {
                  const w = WORKFLOWS.find(x => x.slug === slug);
                  return <button key={slug} className="tag tag-accent" onClick={() => go('workflow', slug)} style={{ cursor: 'pointer' }}>{w ? w.name : slug}</button>;
                })}
              </div>
            </div>

            <div style={{ marginTop: 32 }}>
              <div className="kicker" style={{ marginBottom: 12 }}>Stack they currently use</div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                {p.saas.map(s => <span key={s} className="tag mono" style={{ fontSize: 11 }}>{s}</span>)}
              </div>
            </div>

            <div style={{ marginTop: 48, paddingTop: 32, borderTop: '1px solid var(--line)' }}>
              <div className="kicker" style={{ marginBottom: 16 }}>Reviews of operators they've worked with</div>
              <div className="card" style={{ padding: 32, textAlign: 'center', color: 'var(--ink-3)' }}>
                <p style={{ margin: 0, fontSize: 14 }}>No reviews yet — this poster is new to HumansRunIt.</p>
                <p style={{ margin: '6px 0 0', fontSize: 13 }}>Reviews appear here after the first delivered workflow.</p>
              </div>
            </div>
          </div>

          <aside>
            <div className="card" style={{ padding: 24, position: 'sticky', top: 80 }}>
              <div className="kicker" style={{ marginBottom: 12 }}>Practical</div>
              <div className="spec-row"><div className="spec-label">Budget</div><div>{p.budget || '—'}</div></div>
              <div className="spec-row"><div className="spec-label">Region</div><div>{p.region}</div></div>
              <div className="spec-row"><div className="spec-label">Industry</div><div>{p.industry}</div></div>
              <div className="spec-row"><div className="spec-label">Posted</div><div>{p.posted}</div></div>
              <button className="btn btn-primary" style={{ marginTop: 20, width: '100%' }} onClick={() => setContactOpen(true)}>Reach out <Icon.arrow /></button>
              <p className="muted" style={{ fontSize: 11, textAlign: 'center', marginTop: 12 }}>Free. No middleman. Deal directly.</p>
            </div>
          </aside>
        </div>
      </section>

      {contactOpen && (
        <div onClick={() => setContactOpen(false)} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.4)', backdropFilter: 'blur(4px)', display: 'grid', placeItems: 'center', zIndex: 100 }}>
          <div onClick={e => e.stopPropagation()} className="card" style={{ width: 'min(520px, 90vw)', padding: 32, background: 'var(--bg-1)' }}>
            <Kicker>Reach out</Kicker>
            <h3 style={{ fontSize: 22, fontWeight: 500, marginTop: 8 }}>Send a message to {p.business}</h3>
            <textarea className="textarea" rows={5} style={{ marginTop: 16 }} placeholder="Hi — I deliver missed-call text-back for service businesses. I'd love to hear more about your setup…" />
            <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8, marginTop: 16 }}>
              <button className="btn" onClick={() => setContactOpen(false)}>Cancel</button>
              <button className="btn btn-primary" onClick={() => { setContactOpen(false); go('inbox'); }}>Send <Icon.arrow /></button>
            </div>
          </div>
        </div>
      )}
    </>
  );
}

function SearchResultsPage({ go, query }) {
  // query: { q, workflow, industry, region, language }
  const { OPERATORS, WORKFLOWS, INDUSTRIES } = window.HRI_DATA;
  const [filters, setFilters] = useStateX(query || { q: 'receptionist', workflow: 'ai-receptionist', industry: 'Salons & beauty', region: 'US', language: null });

  const removeFilter = (key) => setFilters(f => ({ ...f, [key]: null }));

  const results = OPERATORS.filter(o => {
    if (filters.workflow && !o.workflows.includes(filters.workflow)) return false;
    if (filters.industry && !o.industries.includes(filters.industry)) return false;
    if (filters.region && !o.region.toLowerCase().includes(filters.region.toLowerCase())) return false;
    if (filters.language && !o.languages.includes(filters.language)) return false;
    if (filters.q && !(o.name + ' ' + o.bio).toLowerCase().includes(filters.q.toLowerCase())) return false;
    return true;
  });

  const activeChips = [
    filters.q && ['q', `"${filters.q}"`],
    filters.workflow && ['workflow', WORKFLOWS.find(w => w.slug === filters.workflow)?.name || filters.workflow],
    filters.industry && ['industry', filters.industry],
    filters.region && ['region', filters.region],
    filters.language && ['language', filters.language],
  ].filter(Boolean);

  const urlExample = `/operators?${activeChips.map(([k, v]) => `${k}=${encodeURIComponent(String(v).toLowerCase().replace(/\s+/g, '-'))}`).join('&')}`;

  return (
    <section style={{ padding: '40px 0 80px' }}>
      <div className="container">
        <div style={{ marginBottom: 24 }}>
          <Kicker>Search results · operators</Kicker>
          <h1 className="h2" style={{ fontSize: 'clamp(28px, 3vw, 40px)', marginTop: 8, lineHeight: 1.1 }}>
            {results.length} operator{results.length === 1 ? '' : 's'} match
          </h1>
          <code className="mono" style={{ display: 'inline-block', marginTop: 12, fontSize: 11, color: 'var(--ink-3)', background: 'var(--bg-1)', padding: '4px 10px', borderRadius: 4, border: '1px solid var(--line)' }}>
            {urlExample || '/operators'}
          </code>
        </div>

        {activeChips.length > 0 && (
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, alignItems: 'center', padding: '16px 0', borderTop: '1px solid var(--line)', borderBottom: '1px solid var(--line)', marginBottom: 24 }}>
            <span className="kicker" style={{ marginRight: 8 }}>Active filters</span>
            {activeChips.map(([k, v]) => (
              <button key={k} onClick={() => removeFilter(k)} className="tag tag-accent" style={{ cursor: 'pointer', paddingRight: 6 }}>
                <span className="mono" style={{ fontSize: 10, opacity: 0.7, textTransform: 'uppercase' }}>{k}:</span> {v}
                <span style={{ display: 'inline-grid', placeItems: 'center', width: 16, height: 16, borderRadius: 999, background: 'color-mix(in oklab, var(--accent) 25%, transparent)', marginLeft: 4, fontSize: 11 }}>×</span>
              </button>
            ))}
            <button className="btn btn-ghost btn-sm" style={{ marginLeft: 'auto', fontSize: 12 }} onClick={() => setFilters({ q: null, workflow: null, industry: null, region: null, language: null })}>Clear all</button>
          </div>
        )}

        <div className="grid grid-3">
          {results.map(o => (
            <button key={o.id} className="card" onClick={() => go('operator', o.id)} style={{ padding: 24, textAlign: 'left', cursor: 'pointer', border: '1px solid var(--line)', background: 'var(--bg-1)' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <Avatar initials={o.initials} size={48} />
                <div>
                  <div style={{ fontWeight: 500, fontSize: 16 }}>{o.name}</div>
                  <div className="mono" style={{ fontSize: 11, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.05em' }}>{o.region}</div>
                </div>
              </div>
              <p style={{ color: 'var(--ink-2)', fontSize: 14, marginTop: 14, lineHeight: 1.4 }}>{o.bio.slice(0, 110)}…</p>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 16, paddingTop: 14, borderTop: '1px solid var(--line)' }}>
                <span style={{ fontSize: 13, color: 'var(--accent-2)' }}><Icon.star /> {o.rating} · {o.delivered} delivered</span>
                <Icon.arrow />
              </div>
            </button>
          ))}
        </div>

        {results.length === 0 && (
          <div className="card" style={{ padding: 64, textAlign: 'center', color: 'var(--ink-3)' }}>
            <p style={{ fontSize: 17, color: 'var(--ink-2)' }}>No operators match these filters.</p>
            <p style={{ fontSize: 14, marginTop: 8 }}>Try removing a chip above, or post your problem and let operators find you.</p>
            <button className="btn btn-primary" style={{ marginTop: 16 }} onClick={() => go('problem-edit')}>Post a problem <Icon.arrow /></button>
          </div>
        )}
      </div>
    </section>
  );
}

Object.assign(window, { ProblemDetailPage, SearchResultsPage });
