// BookUno Web — Discover page (consumer marketplace)

const { useState: useStateDisc, useEffect: useEffectDisc } = React;

// Human label + city for a real business row (no invented ratings/slots).
function bizTypeLabel(type) {
  if (!type) return 'Local service';
  const g = (window.SERVICE_GROUPS || []).find(x => x.id === type);
  if (g) return g.name;
  return String(type).replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase());
}
function bizCity(address) {
  if (!address) return '';
  if (typeof address === 'string') return address;
  return address.city || address.town || '';
}

function RealBizCard({ b, delay = 0 }) {
  const href = b.slug ? `/b/${b.slug}` : '/#/search';
  const city = bizCity(b.address);
  return (
    <Rv delay={delay}>
      <a href={href} className="sf-card">
        <div className="cover" style={{ position: 'relative' }}>
          <Cover seed={(b.name || '').length} h={180} r={0} label={bizTypeLabel(b.type)} photo={b.logo_url || null}/>
        </div>
        <div className="body" style={{ padding: 16 }}>
          <div style={{ fontWeight: 800, fontSize: 16, letterSpacing: -0.015 }}>{b.name}</div>
          <div style={{ fontSize: 12.5, color: 'var(--muted)', marginTop: 4, display: 'flex', alignItems: 'center', gap: 6 }}>
            <Ic.pin style={{ width: 12, height: 12 }}/>{[bizTypeLabel(b.type), city].filter(Boolean).join(' · ')}
          </div>
          <div style={{ marginTop: 12 }}>
            <span className="btn primary sm" style={{ pointerEvents: 'none' }}>View &amp; book</span>
          </div>
        </div>
      </a>
    </Rv>
  );
}

function PageDiscover({ logoVariant = 'default' }) {
  const [cat, setCat] = useStateDisc('all');
  const [q, setQ] = useStateDisc('');
  const [businesses, setBusinesses] = useStateDisc(null); // null = loading
  const [loadErr, setLoadErr] = useStateDisc(false);

  useEffectDisc(() => {
    let cancelled = false;
    const api = window.BOOKUNO_API;
    if (!api || typeof api.listPublicBusinesses !== 'function') { setBusinesses([]); return; }
    api.listPublicBusinesses('', '')
      .then(rows => { if (!cancelled) setBusinesses(Array.isArray(rows) ? rows : []); })
      .catch(() => { if (!cancelled) { setBusinesses([]); setLoadErr(true); } });
    return () => { cancelled = true; };
  }, []);

  const all = businesses || [];
  const nearYou = all.filter(b => {
    if (!q) return true;
    return (`${b.name} ${bizTypeLabel(b.type)}`).toLowerCase().includes(q.toLowerCase());
  });

  return (
    <div className="web">
      <TopNav active="discover" logoVariant={logoVariant}/>

      {/* ─── SEARCH HERO ─── */}
      <section className="disc-hero">
        <div className="container">
          <Rv>
            <a href="#" className="disc-loc"><Ic.pin style={{ width: 14, height: 14 }}/> United Kingdom · <span>change</span></a>
          </Rv>
          <Rv delay={60}>
            <h1 className="disc-h1">Book great local businesses across the UK.</h1>
          </Rv>
          <Rv delay={120}>
            <p className="disc-sub">Find local businesses and send your booking request in seconds. Free for customers, always.</p>
          </Rv>
          <Rv delay={180}>
            <form className="disc-search" onSubmit={(e) => { e.preventDefault(); window.location.href = `/#/search${q ? '?q=' + encodeURIComponent(q) : ''}`; }}>
              <div className="disc-search-field">
                <Ic.search style={{ width: 18, height: 18, color: 'var(--muted)' }}/>
                <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Service or business — e.g. skin fade, massage"/>
              </div>
              <div className="disc-search-field where">
                <Ic.pin style={{ width: 18, height: 18, color: 'var(--muted)' }}/>
                <input placeholder="Town or city"/>
              </div>
              <button type="submit" className="disc-search-go">Search</button>
            </form>
          </Rv>
          <Rv delay={240}>
            <div className="disc-pop">
              <span>Popular:</span>
              {['Skin fade', 'Gel nails', 'Sports massage', 'Deep clean', 'Dog grooming'].map(t => (
                <button key={t} className="disc-pop-chip" onClick={() => setQ(t)}>{t}</button>
              ))}
            </div>
          </Rv>
        </div>
      </section>

      {/* ─── CATEGORY BROWSE ─── */}
      <section className="section" id="categories" style={{ background: '#fff', paddingTop: 8 }}>
        <div className="container">
          <div className="disc-row-head">
            <div>
              <Rv><div className="micro" style={{ color: 'var(--pri)' }}>BROWSE</div></Rv>
              <Rv delay={60}><h2 className="disc-h2">What do you need today?</h2></Rv>
            </div>
            <Rv delay={60}><a href="/#/categories" className="disc-seeall">All categories →</a></Rv>
          </div>
          <div className="cats">
            <Rv>
              <button className={`cat-tile ${cat === 'all' ? 'on' : ''}`} onClick={() => setCat('all')}>
                <span className="cat-ic" style={{ background: 'var(--pri-50)', color: 'var(--pri)' }}><Ic.spark style={{ width: 22, height: 22 }}/></span>
                <span className="cat-name">All</span>
              </button>
            </Rv>
            {CATEGORIES.slice(0, 11).map((c, i) => {
              const Icon = c.icon;
              return (
                <Rv key={c.id} delay={(i + 1) * 30}>
                  <button
                    className={`cat-tile${c.photo ? ' has-photo' : ''} ${cat === c.id ? 'on' : ''}`}
                    style={c.photo ? { '--cat-bg': `url("${c.photo}")` } : gradVars(c.seed)}
                    onClick={() => setCat(c.id)}>
                    <span className="cat-ic" style={c.photo ? {} : gradVars(c.seed)}><Icon style={{ width: 20, height: 20 }}/></span>
                    <span className="cat-name">{c.name}</span>
                  </button>
                </Rv>
              );
            })}
          </div>
        </div>
      </section>

      {/* ─── NEAR YOU ─── */}
      <section className="section" style={{ background: 'var(--bg)' }}>
        <div className="container">
          <div className="disc-row-head">
            <div>
              <Rv><div className="micro" style={{ color: 'var(--pri)' }}>ON BOOKUNO · UK</div></Rv>
              <Rv delay={60}><h2 className="disc-h2">Local businesses on Bookuno</h2></Rv>
            </div>
            {nearYou.length > 0 && <Rv delay={60}><a href="/#/search" className="disc-seeall">View all →</a></Rv>}
          </div>
          {businesses === null ? (
            <p style={{ color: 'var(--muted)', fontSize: 14, padding: '24px 0' }}>Loading local businesses…</p>
          ) : nearYou.length > 0 ? (
            <div className="sf-grid">
              {nearYou.map((b, i) => <RealBizCard key={b.id} b={b} delay={i * 40}/>)}
            </div>
          ) : (
            <div className="disc-cta" style={{ marginTop: 8 }}>
              <div>
                <div className="disc-cta-t">{q ? `No matches for "${q}" yet` : "We're just getting started"}</div>
                <div className="disc-cta-s">Bookuno is onboarding its first local businesses. Check back soon — or if you run one, get listed free.</div>
              </div>
              <a href="/#/business" className="btn primary lg">Get listed <Ic.arrow style={{ width: 16, height: 16 }}/></a>
            </div>
          )}
        </div>
      </section>

      {/* ─── HELP / VALUE STRIP ─── */}
      <section className="section" id="help" style={{ background: 'var(--bg)' }}>
        <div className="container">
          <div className="disc-help">
            {[
              { ic: Ic.shield, t: 'Clear policies up front', d: 'Each business sets its own cancellation policy — shown before you book.' },
              { ic: Ic.spark, t: 'Book direct', d: 'Message and book local businesses directly, right from their page.' },
              { ic: Ic.spark, t: 'No booking fees', d: 'You pay the business directly — Bookuno never adds a surcharge.' },
            ].map((x, i) => {
              const Icon = x.ic;
              return (
                <Rv key={i} delay={i * 60}>
                  <div className="disc-help-card">
                    <span className="disc-help-ic"><Icon style={{ width: 20, height: 20, color: 'var(--pri)' }}/></span>
                    <div className="disc-help-t">{x.t}</div>
                    <div className="disc-help-d">{x.d}</div>
                  </div>
                </Rv>
              );
            })}
          </div>
          <Rv delay={200}>
            <div className="disc-cta">
              <div>
                <div className="disc-cta-t">Run a business? Get listed free.</div>
                <div className="disc-cta-s">Now accepting early businesses across the UK. Free setup, personal onboarding.</div>
              </div>
              <a href="/#/business" className="btn primary lg">For business <Ic.arrow style={{ width: 16, height: 16 }}/></a>
            </div>
          </Rv>
        </div>
      </section>

      <Footer logoVariant={logoVariant}/>
    </div>
  );
}

Object.assign(window, { PageDiscover });
