// Shared discovery routes retain their existing search behavior.
function PageHome(props){return <FrameCustomerHome {...props}/>;}

/* ─── Reusable storefront card ────────────────────────────── */
// Renders ONLY fields that come from the business's own record. It previously
// showed a hardcoded 4.9 rating, a hardcoded "from £18" and three invented
// availability slots ("Tomorrow 14:00") for every business — fabricated ratings,
// prices and availability shown to real customers. Real availability lives on
// the storefront, which queries the business's actual services and hours.
function SFCard({ b, delay = 0 }) {
  const href = b.slug ? `/app.html#/b/${b.slug}` : '/app.html#/search';
  const meta = [b.catLabel, b.dist].filter(Boolean).join(' · ');
  return (
    <Rv delay={delay}>
      <a href={href} className="sf-card">
        <div className="cover" style={{ position: 'relative' }}>
          <Cover seed={b.seed} h={180} r={0} label={b.catLabel || uiText("Business")} photo={b.logo_url || null}/>
        </div>
        <div className="body" style={{ padding: 16 }}>
          <div style={{ fontWeight: 800, fontSize: 16, letterSpacing: -0.015 }}>{b.name}</div>
          {meta && (
            <div style={{ fontSize: 12.5, color: 'var(--muted)', marginTop: 4, display: 'flex', alignItems: 'center', gap: 6 }}>
              <Ic.pin style={{ width: 12, height: 12 }}/>{meta}
            </div>
          )}
          <div style={{ marginTop: 12 }}>
            <span className="btn primary sm" style={{ pointerEvents: 'none' }}>{uiText("View business")}</span>
          </div>
        </div>
      </a>
    </Rv>
  );
}

/* ─── Search empty state ──────────────────────────────────── */
// Same Supabase functions origin the rest of the client uses.
const SUGGEST_ENDPOINT = (function () {
  var base = (window.BOOKUNO_CONFIG && window.BOOKUNO_CONFIG.supabaseUrl) || '';
  return base ? base.replace(/\/$/, '') + '/functions/v1/suggest-business' : '';
})();

function SearchEmptyState({ query, category, onClear }) {
  const [suggestName, setSuggestName] = React.useState('');
  const [suggestType, setSuggestType] = React.useState('');
  const [sent, setSent] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [sendErr, setSendErr] = React.useState('');

  // This used to open a mailto: and immediately claim "We'll reach out to
  // <name>" — a promise on a form that persisted nothing and notified nobody if
  // the visitor's mail client was blocked or they never sent the draft. It now
  // posts to the suggest-business edge function, which writes a row to `leads`
  // where it shows up in /admin. The success message is only shown once the
  // server has actually accepted it.
  async function handleSuggest(e) {
    e.preventDefault();
    const name = suggestName.trim();
    if (!name || sending) return;
    setSending(true);
    setSendErr('');
    try {
      const res = await fetch(SUGGEST_ENDPOINT, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name, business_type: suggestType.trim() || null, notes: 'Suggested from Bookuno search' }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(data.error || 'Could not send that just now.');
      setSent(true);
    } catch (err) {
      setSendErr(err?.message || 'Could not send that just now. Please try again.');
    } finally {
      setSending(false);
    }
  }

  return (
    <div style={{ padding: '60px 24px', textAlign: 'center', maxWidth: 480, margin: '0 auto' }}>
      <div style={{ fontSize: 42, marginBottom: 16 }}>📍</div>
      <h3 style={{ fontSize: 20, fontWeight: 800, letterSpacing: -0.02, marginBottom: 8 }}>
        Still growing in this area
      </h3>
      <p style={{ fontSize: 14, color: 'var(--muted)', lineHeight: 1.6, marginBottom: 24 }}>
        Bookuno is launching across the UK — more businesses are joining every week.
        {query && <> No results yet for <b>"{query}"</b>.</>}
      </p>
      {(query || category) && (
        <button className="btn outline sm" onClick={onClear} style={{ marginBottom: 20 }}>Clear search</button>
      )}
      {!sent ? (
        <div style={{ padding: 20, borderRadius: 16, background: 'var(--bg)', border: '1px solid var(--line)', textAlign: 'left' }}>
          <div style={{ fontWeight: 800, fontSize: 14, marginBottom: 4 }}>Know a business that should be here?</div>
          <p style={{ fontSize: 13, color: 'var(--muted)', marginBottom: 14 }}>Suggest them and we'll reach out to get them listed.</p>
          <form onSubmit={handleSuggest} style={{ display: 'grid', gap: 10 }}>
            <input
              value={suggestName}
              onChange={e => setSuggestName(e.target.value)}
              placeholder="Business name (required)"
              style={{ width: '100%', border: '1.5px solid var(--line)', borderRadius: 10, padding: '9px 12px', fontSize: 13.5, fontWeight: 600, outline: 'none', background: '#fff', boxSizing: 'border-box' }}
            />
            <input
              value={suggestType}
              onChange={e => setSuggestType(e.target.value)}
              placeholder="Type of business — e.g. barber, cleaner"
              style={{ width: '100%', border: '1.5px solid var(--line)', borderRadius: 10, padding: '9px 12px', fontSize: 13.5, fontWeight: 600, outline: 'none', background: '#fff', boxSizing: 'border-box' }}
            />
            <button type="submit" className="btn primary sm block" style={{ height: 42 }} disabled={sending}>
              {sending ? 'Sending…' : 'Suggest this business →'}
            </button>
            {sendErr && <div role="alert" style={{ fontSize: 12.5, color: 'var(--danger, #C0392B)', fontWeight: 600 }}>{sendErr}</div>}
          </form>
        </div>
      ) : (
        <div style={{ padding: 20, borderRadius: 16, background: 'var(--pri-50)', border: '1px solid var(--pri)', textAlign: 'center' }}>
          <div style={{ fontSize: 28, marginBottom: 8 }}>🙌</div>
          <div style={{ fontWeight: 800, fontSize: 15, color: 'var(--pri-700)', marginBottom: 4 }}>Thanks for the tip!</div>
          <p style={{ fontSize: 13, color: 'var(--pri-700)' }}>We've got {suggestName} on our list. We reach out to suggested businesses ourselves — there's nothing else for you to do.</p>
        </div>
      )}
      <div style={{ marginTop: 24, paddingTop: 20, borderTop: '1px solid var(--line-2)' }}>
        <div style={{ fontSize: 13, color: 'var(--muted)', marginBottom: 12 }}>Are you a business owner?</div>
        <a href="/#/business" className="btn primary sm">Get listed free →</a>
      </div>
    </div>
  );
}

/* ─── Search results page (desktop layout) ────────────────── */
const { useState, useEffect } = React;
function PageSearch({ logoVariant = 'default', loggedIn = true }) {
  const getInitialParams = () => {
    try {
      const hash = window.location.hash || '';
      const qIndex = hash.indexOf('?');
      if (qIndex === -1) return { q: '', cat: '', loc: '' };
      const params = new URLSearchParams(hash.slice(qIndex + 1));
      const raw=params.get('cat')||'',cat=raw==='camp'?'campsite':raw==='hire'?'rental':raw;
      return { q: params.get('q') || '', cat, loc: params.get('loc') || '' };
    } catch { return { q: '', cat: '', loc: '' }; }
  };

  const initial = getInitialParams();
  const [query, setQuery] = useState(initial.q);
  const [category, setCategory] = useState(initial.cat);
  const [locationText, setLocationText] = useState(initial.loc);
  const [businesses, setBusinesses] = useState([]);
  const [loading, setLoading] = useState(true);
  const [searching, setSearching] = useState(false);
  const [error, setError] = useState(null);
  const searchVersion=React.useRef(0),searchLive=React.useRef(true);

  const doSearch = (q, cat, loc=locationText) => {
    const params=new URLSearchParams();if(q.trim())params.set('q',q.trim());if(cat)params.set('cat',cat);if(loc.trim())params.set('loc',loc.trim());
    window.history?.replaceState?.(window.history.state,'','#/search'+(params.size?'?'+params.toString():''));
    const token=++searchVersion.current;
    setSearching(true);setLoading(true);setBusinesses([]);
    setError(null);
    const api = window.BOOKUNO_API;
    if (!api || typeof api.listPublicBusinesses !== 'function') {
      setLoading(false);
      setSearching(false);
      setError("API not available");
      return;
    }
    api.listPublicBusinesses(q, cat)
      .then(data => {
        if(!searchLive.current||token!==searchVersion.current)return;
        if(!Array.isArray(data))throw Error('Business details could not be loaded.');
        setBusinesses(data);
        setLoading(false);
        setSearching(false);
      })
      .catch(err => {
        if(!searchLive.current||token!==searchVersion.current)return;
        setError("Business details could not be loaded. Please try again.");
        setLoading(false);
        setSearching(false);
      });
  };

  useEffect(() => {searchLive.current=true;doSearch(query, category);return()=>{searchLive.current=false;searchVersion.current++;};}, []);

  const clearSearch=()=>{setQuery('');setCategory('');setLocationText('');doSearch('','','');};

  const handleSearch = (e) => {
    e && e.preventDefault();
    doSearch(query, category);
  };

  // Address helpers — businesses carry a JSONB `address` (city/postcode/formatted).
  const addressText = (b) => {
    const a = b.address;
    if (!a) return '';
    if (typeof a === 'string') return a;
    return [a.line1, a.line2, a.city, a.region, a.postcode, a.formatted].filter(Boolean).join(' ');
  };
  const areaLabel = (b) => {
    const a = b.address;
    if (!a) return 'Location not provided';
    if (typeof a === 'string') return a;
    return a.city || a.region || a.postcode || 'Location not provided';
  };

  // Location filter — narrows results to the area the user typed ("search around them").
  // Businesses that haven't published an address yet are kept visible (we can't
  // confirm they're elsewhere) so a location search never hides everything.
  const locNeedle = locationText.trim().toLowerCase();
  const filteredBiz = locNeedle
    ? businesses.filter(b => { const hay = addressText(b).toLowerCase(); return !hay || hay.includes(locNeedle); })
    : businesses;

  const cards = filteredBiz.map((b, i) => ({
    id: b.id,
    name: b.name,
    slug: b.slug,
    seed: i,
    cat: b.type,
    catLabel: customerHomeCategoryLabel(b.type),
    logo_url: b.logo_url || null,
    dist: areaLabel(b),
  }));

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

      {/* Search header */}
      <section style={{ background: '#fff', borderBottom: '1px solid var(--line)', padding: '28px 0 22px' }}>
        <div className="container">
          <h1 style={{fontSize:30,fontWeight:650,letterSpacing:'-.035em',lineHeight:1.2,marginBottom:22}}>{uiText("Find a business.")}</h1>
          <form onSubmit={handleSearch} style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
            <input
              value={query}
              onChange={e => setQuery(e.target.value)}
              placeholder={uiText("Search businesses…")}
              aria-label={uiText("Business name")}
              style={{ flex: '2 1 200px', height: 44, borderRadius: 10, border: '1.5px solid var(--line)', padding: '0 14px', fontSize: 16, fontWeight: 600, outline: 'none' }}
            />
            <div style={{ position: 'relative', flex: '1 1 150px', display: 'flex', alignItems: 'center' }}>
              <Ic.pin style={{ width: 15, height: 15, position: 'absolute', left: 12, color: 'var(--muted)', pointerEvents: 'none' }}/>
              <input
                value={locationText}
                onChange={e => setLocationText(e.target.value)}
                placeholder={uiText("Town, city or postcode")}
                aria-label={uiText("Location")}
                style={{ width: '100%', height: 44, borderRadius: 10, border: '1.5px solid var(--line)', padding: '0 12px 0 34px', fontSize: 16, fontWeight: 600, outline: 'none' }}
              />
            </div>
            <select aria-label={uiText("Business category")} value={category} onChange={e=>{setCategory(e.target.value);doSearch(query,e.target.value);}} style={{flex:'1 1 160px',minHeight:44,minWidth:0,borderRadius:9,border:'1px solid var(--line)',padding:'9px 12px',background:'#fff',fontSize:14,color:'var(--ink)'}}><option value="">{uiText("All categories")}</option>{category&&!CUSTOMER_BUSINESS_CATEGORIES.some(([id])=>id===category)&&<option value={category}>{customerHomeCategoryLabel(category)||uiText("Selected category")}</option>}{CUSTOMER_BUSINESS_CATEGORIES.map(([id,label])=><option key={id} value={id}>{uiText(label)}</option>)}</select>
            <button type="submit" aria-label={uiText("Search businesses")} className="btn primary sm" style={{ height: 44, minWidth: 44 }}>
              <Ic.search style={{ width: 16, height: 16 }}/> <span className="hide-mobile">{uiText("Search")}</span>
            </button>
            <button className="btn outline sm" type="button" style={{minHeight:44}} onClick={clearSearch}>{uiText("Clear search")}</button>
            {searching && <span style={{ fontSize: 13, color: 'var(--muted)', fontWeight: 600 }}>{uiText("Searching…")}</span>}
            {!loading && !searching && (
              <span className="muted" style={{ fontSize: 14 }}>
                · <b style={{ color: 'var(--ink)' }}>{cards.length}</b> {cards.length === 1 ? uiText("business") : uiText("businesses")}
              </span>
            )}
          </form><p style={{fontSize:12,color:'var(--muted)',lineHeight:1.7,marginTop:14}}>{uiText("Check a business page for its current offers, prices and availability.")}</p>
        </div>
      </section>

      {/* Two-column results */}
      <div className="search-shell">
        {/* Results */}
        <div style={{ flex: 1, minWidth: 0 }}>
          {/* Initial load skeleton — only shown when no results yet */}
          {loading && businesses.length === 0 && (
            <div className="results-grid">
              {[0,1,2].map(i => (
                <div key={i} className="sf-card" style={{ pointerEvents: 'none' }}>
                  <div style={{ height: 180, background: 'linear-gradient(90deg, var(--chip) 25%, var(--line) 50%, var(--chip) 75%)', backgroundSize: '200% 100%', animation: 'shimmer 1.4s infinite', borderRadius: '14px 14px 0 0' }}/>
                  <div style={{ padding: 16 }}>
                    <div style={{ height: 16, borderRadius: 8, background: 'var(--chip)', marginBottom: 8, width: '70%' }}/>
                    <div style={{ height: 13, borderRadius: 8, background: 'var(--chip)', width: '45%' }}/>
                  </div>
                </div>
              ))}
            </div>
          )}
          {!loading && error && (
            <div style={{ padding: '60px 0', textAlign: 'center', color: 'var(--muted)' }}>
              <div role="alert" style={{ fontWeight: 600, color: 'var(--red, #DC2626)' }}>{uiText(error)}</div><button className="btn outline" type="button" style={{minHeight:44,marginTop:16}} onClick={()=>doSearch(query,category)}>{uiText("Retry search")}</button>
            </div>
          )}
          {!loading && !searching && !error && cards.length === 0 && (
            <div className="ch-notice"><h2>{uiText("No matching businesses")}</h2><p>{uiText("Try a different name, category or location. Businesses appear here when they choose to publish their listing.")}</p><p>{uiText("Use Clear search above to remove the current filters.")}</p></div>
          )}
          {/* Show results — keep visible even while re-searching */}
          {!loading && !error && cards.length > 0 && (
            <div className="results-grid" style={{ opacity: searching ? 0.6 : 1, transition: 'opacity 0.2s' }}>
              {cards.map((b, i) => <SFCard key={b.id || i} b={b} delay={i * 30}/>)}
            </div>
          )}
        </div>
      </div>

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

function FilterGroup({ label, children }) {
  return (
    <div style={{ paddingBottom: 16, marginBottom: 16, borderBottom: '1px solid var(--line-2)' }}>
      <div style={{ fontSize: 12, fontWeight: 800, letterSpacing: 0.05, textTransform: 'uppercase', color: 'var(--muted)', marginBottom: 10 }}>{label}</div>
      <div style={{ display: 'grid', gap: 6 }}>{children}</div>
    </div>
  );
}
function CheckLine({ label, checked = false, count }) {
  return (
    <label style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 13.5, cursor: 'pointer', padding: '2px 0' }}>
      <span style={{ width: 18, height: 18, borderRadius: 5, background: checked ? 'var(--pri)' : '#fff', border: checked ? 'none' : '1.5px solid var(--line)', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
        {checked && <Ic.check style={{ width: 11, height: 11, color: '#fff' }}/>}
      </span>
      <span style={{ flex: 1, display: 'inline-flex', alignItems: 'center', gap: 5 }}>{label}</span>
      {count && <span style={{ fontSize: 11.5, color: 'var(--muted-2)' }}>{count}</span>}
    </label>
  );
}
function RangeMock({ value = 5, max = 25 }) {
  const pct = (value / max) * 100;
  return (
    <div style={{ padding: '6px 0' }}>
      <div style={{ height: 6, borderRadius: 6, background: 'var(--line)', position: 'relative' }}>
        <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: `${pct}%`, background: 'var(--pri)', borderRadius: 6 }}/>
        <div style={{ position: 'absolute', left: `${pct}%`, top: '50%', transform: 'translate(-50%, -50%)', width: 18, height: 18, borderRadius: '50%', background: '#fff', boxShadow: 'var(--sh-2), 0 0 0 1.5px var(--pri)' }}/>
      </div>
    </div>
  );
}

Object.assign(window, { PageHome, PageSearch, SFCard });
