/* ============================================================
   Considered · Brand detail, Category, Cluster, Search  (window.GGBrand)
   ============================================================ */
const { useState: useSB } = React;
const BC = window.GGComp;
const BU = window.GGUtil;
const BD = window.GG;
const BIc = window.GGIcons;
const BRes = window.GGResults;
const { SectionHead: BSectionHead } = window.GGHome;

/* ============================================================
   BRAND DETAIL — the hardest-working screen
   ============================================================ */
const BrandDetailScreen = ({ params, t }) => {
  const nav = BC.useNav();
  const b = BD.BY_SLUG[params.slug];
  if (!b) return <div className="gg-container gg-section"><p>Brand not found.</p></div>;
  const related = BU.relatedTo(b, 6);
  const a = BU.age(b);
  const textOnly = true; // always text-only until product photography is added

  const HeroInfo = ({ band }) => (
    <div style={{ padding: band ? 'clamp(28px,4vw,46px)' : 'clamp(24px,3vw,38px)', display: 'flex', flexDirection: 'column', gap: 14 }}>
      <div className="gg-wrap">
        <BC.HeritageBadge brand={b} withNote />
        {b.tags.includes('Family-run') && <BC.Tag>Family-run</BC.Tag>}
      </div>
      <div>
        <h1 className="gg-display" style={{ fontSize: band ? 'clamp(40px,6vw,76px)' : 'clamp(36px,5vw,64px)', maxWidth: '16ch' }}>{b.name}</h1>
        <div className="gg-row" style={{ gap: 12, marginTop: 8, flexWrap: 'wrap' }}>
          <span className="gg-row" style={{ gap: 6 }}><BIc.Pin size={16} style={{ color: 'var(--coral-400)' }} /> <span className="gg-meta" style={{ fontSize: 15, color: 'var(--plum-800)', fontWeight: 600 }}>{b.country}</span></span>
          {b.founded && <span className="gg-row" style={{ gap: 6 }}><BIc.Clock size={16} style={{ color: 'var(--coral-400)' }} /> <span className="gg-meta" style={{ fontSize: 15, color: 'var(--plum-800)', fontWeight: 600 }}>Est. {b.founded}{a ? ` · ${a} years` : ''}</span></span>}
        </div>
      </div>
      <div className="gg-row" style={{ gap: 12 }}>
        <BC.Price band={b.priceBand} style={{ fontSize: 20 }} />
        <span className="gg-meta">{BD.PRICE[b.priceBand].label}</span>
      </div>
      <p style={{ margin: '4px 0 0', fontSize: 'clamp(16px,1.7vw,19px)', lineHeight: 1.6, color: 'var(--fg-1)', maxWidth: band ? '64ch' : 'none' }}>{b.fullDescription || b.description}</p>
      {band && (
        <div style={{ marginTop: 2 }}>
          <span className="gg-meta" style={{ fontWeight: 700, color: 'var(--plum-800)', display: 'block', marginBottom: 8 }}>Great for</span>
          <div className="gg-wrap">
            {b.greatFor.map(g => <span key={g} className="gg-chip" style={{ background: 'var(--milk-50)', fontSize: 13 }}><BIc.Gift size={13} strokeWidth={2} />{g}</span>)}
          </div>
        </div>
      )}
      <div className="gg-wrap" style={{ marginTop: band ? 8 : 'auto', paddingTop: 10, gap: 12 }}>
        <a href={b.url} target="_blank" rel="noopener noreferrer" className="gg-btn gg-btn-pop" style={{ textDecoration: 'none' }}>
          <BIc.External size={17} /> Where to buy
        </a>
        <button className="gg-btn gg-btn-secondary" onClick={() => nav.go('category', { cat: b.primary })}>More in {b.primary}</button>
      </div>
    </div>
  );

  return (
    <div className="gg-container gg-section">
      <button className="gg-btn gg-btn-ghost gg-btn-sm" onClick={() => nav.back()} style={{ padding: '4px 8px', marginBottom: 14 }}><BIc.ArrowL size={16} /> Back</button>

      {/* Hero */}
      {textOnly ? (
        <div className={`gg-card t-${b.tint}`} style={{ padding: 0, overflow: 'hidden', marginBottom: 36 }}>
          <HeroInfo band />
        </div>
      ) : (
        <div className="gg-card" style={{ padding: 0, overflow: 'hidden', display: 'grid', gridTemplateColumns: 'minmax(0,0.85fr) minmax(0,1.15fr)', marginBottom: 36 }}>
          <div className={`t-${b.tint}`} style={{ minHeight: 320, borderRight: '1.5px solid var(--plum-800)' }}>
            {React.createElement('image-slot', { id: 'brand-' + b.slug, shape: 'rect', placeholder: 'Drop a photo of ' + b.name, style: { width: '100%', height: '100%', minHeight: 320 } })}
          </div>
          <HeroInfo />
        </div>
      )}

      {/* Signature + Great for + Tags */}
      <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0,1.4fr) minmax(0,1fr)', gap: 24, alignItems: 'start' }}>
        <div className="gg-card" style={{ padding: '24px 26px' }}>
          <BC.Eyebrow>Signature</BC.Eyebrow>
          <h3 className="gg-display gg-h3" style={{ margin: '8px 0 16px' }}>What to actually get</h3>
          <div className="gg-stack" style={{ gap: 0 }}>
            {b.signature.map((s, i) => (
              <div key={i} className="gg-row" style={{ gap: 14, padding: '13px 0', borderTop: i ? '1.5px solid var(--milk-200)' : 'none' }}>
                <span style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 18, color: 'var(--coral-300)', width: 26, flexShrink: 0 }}>{String(i + 1).padStart(2, '0')}</span>
                <span style={{ fontSize: 16, fontWeight: 600, color: 'var(--plum-800)' }}>{s}</span>
              </div>
            ))}
          </div>
        </div>

        <div className="gg-stack" style={{ gap: 20 }}>
          {!textOnly && (
            <div className="gg-card t-pistachio" style={{ padding: '20px 22px' }}>
              <BC.Eyebrow>Great for</BC.Eyebrow>
              <div className="gg-wrap" style={{ marginTop: 12 }}>
                {b.greatFor.map(g => <span key={g} className="gg-chip" style={{ background: 'var(--milk-50)', fontSize: 13 }}><BIc.Gift size={13} strokeWidth={2} />{g}</span>)}
              </div>
            </div>
          )}
          <div className="gg-card" style={{ padding: '20px 22px' }}>
            <BC.Eyebrow>Characteristics</BC.Eyebrow>
            <div className="gg-wrap" style={{ marginTop: 12 }}>
              {b.tags.map(tg => <BC.Tag key={tg}>{tg}</BC.Tag>)}
            </div>
          </div>
          {b.secondary && (
            <div className="gg-card" style={{ padding: '16px 22px' }}>
              <span className="gg-meta" style={{ fontWeight: 700, color: 'var(--plum-800)' }}>Also in</span>
              <div className="gg-wrap" style={{ marginTop: 10 }}>
                <button className="gg-fchip" onClick={() => nav.go('category', { cat: b.secondary })}>{b.secondary}</button>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* Related */}
      {related.length > 0 && (
        <div style={{ marginTop: 48 }}>
          <BSectionHead eyebrow="If you like this" title="Related brands"
            sub="Same category, or kindred in spirit and tags — the discovery rabbit-hole." />
          <BRes.BrandGrid brands={related} variant={t.cardStyle} />
        </div>
      )}
    </div>
  );
};

/* ============================================================
   CATEGORY PAGE
   ============================================================ */
const CategoryScreen = ({ params, t }) => {
  const nav = BC.useNav();
  const cat = params.cat;
  const brands = BU.brandsInCategory(cat);
  const cl = BU.clusterForCat(cat);
  const blurb = BD.CATEGORY_BLURBS[cat] || 'A considered corner of the directory.';
  return (
    <div className="gg-container gg-section">
      <div className="gg-row" style={{ gap: 8, marginBottom: 14, fontSize: 13 }} >
        <button className="gg-btn gg-btn-ghost gg-btn-sm" onClick={() => nav.go('browse')} style={{ padding: '4px 8px' }}>Browse</button>
        <BIc.Chevron size={14} style={{ color: 'var(--fg-3)' }} />
        {cl && <button className="gg-btn gg-btn-ghost gg-btn-sm" onClick={() => nav.go('cluster', { id: cl.id })} style={{ padding: '4px 6px' }}>{cl.title}</button>}
      </div>
      <BC.Eyebrow>{cl ? cl.title : 'Category'}</BC.Eyebrow>
      <h1 className="gg-display gg-h2" style={{ margin: '10px 0 8px' }}>{cat}</h1>
      <p className="gg-meta" style={{ fontSize: 16, maxWidth: '56ch', marginBottom: 28 }}>{blurb}</p>
      <BRes.ResultsView brands={brands} cardStyle={t.cardStyle} defaultSort="heritage" />
    </div>
  );
};

/* ============================================================
   CLUSTER PAGE — subcategories + all brands in the cluster
   ============================================================ */
const ClusterScreen = ({ params, t }) => {
  const nav = BC.useNav();
  const cl = BD.CLUSTERS.find(c => c.id === params.id);
  if (!cl) return <div className="gg-container gg-section"><p>Not found.</p></div>;
  const brands = BU.brandsInCluster(cl.id);
  return (
    <div className="gg-container gg-section">
      <button className="gg-btn gg-btn-ghost gg-btn-sm" onClick={() => nav.go('browse')} style={{ padding: '4px 8px', marginBottom: 14 }}><BIc.ArrowL size={16} /> All categories</button>
      <BC.Eyebrow>Cluster</BC.Eyebrow>
      <h1 className="gg-display gg-h2" style={{ margin: '10px 0 8px' }}>{cl.title}</h1>
      <p className="gg-meta" style={{ fontSize: 16, marginBottom: 18 }}>{cl.blurb}</p>
      <div className="gg-wrap" style={{ marginBottom: 30 }}>
        {cl.cats.map(cat => {
          const n = BU.brandsInCategory(cat).length;
          return <button key={cat} className="gg-fchip" onClick={() => nav.go('category', { cat })}>{cat}{n > 0 && <span style={{ opacity: 0.5 }}>{n}</span>}</button>;
        })}
      </div>
      <BRes.ResultsView brands={brands} cardStyle={t.cardStyle} defaultSort="heritage" />
    </div>
  );
};

/* ============================================================
   SEARCH RESULTS — grouped
   ============================================================ */
const SearchScreen = ({ params, t }) => {
  const nav = BC.useNav();
  const [q, setQ] = useSB(params.q || '');
  const res = BU.search(q);
  const submit = (e) => { e.preventDefault(); };
  const hasAny = res.brands.length || res.categories.length || res.tags.length;

  return (
    <div className="gg-container gg-section">
      <form onSubmit={submit} className="gg-card" style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '8px 8px 8px 18px', maxWidth: 620, boxShadow: '4px 4px 0 var(--plum-800)', marginBottom: 28 }}>
        <BIc.Search size={20} style={{ color: 'var(--plum-800)', flexShrink: 0 }} />
        <input autoFocus value={q} onChange={e => setQ(e.target.value)} placeholder="Search brands, categories, tags…"
          style={{ border: 'none', background: 'transparent', outline: 'none', flex: 1, fontFamily: 'var(--font-body)', fontSize: 17, color: 'var(--fg-1)', minWidth: 0 }} />
        {q && <button type="button" className="gg-btn gg-btn-ghost gg-btn-sm" onClick={() => setQ('')} style={{ padding: 8 }}><BIc.X size={18} /></button>}
      </form>

      {!q.trim() ? (
        <div>
          <span className="gg-meta" style={{ fontWeight: 700, color: 'var(--plum-800)' }}>Try a brand</span>
          <div className="gg-wrap" style={{ marginTop: 12 }}>
            {['Aesop', 'Le Creuset', 'Floris', 'Steiff', 'Pol Roger', 'Marvis'].map(s => (
              <button key={s} className="gg-fchip" onClick={() => setQ(s)}>{s}</button>
            ))}
          </div>
          <span className="gg-meta" style={{ fontWeight: 700, color: 'var(--plum-800)', display: 'block', marginTop: 24 }}>Or a kind of thing</span>
          <div className="gg-wrap" style={{ marginTop: 12 }}>
            {['toothpaste', 'candle', 'watch', 'blanket', 'champagne', 'handmade'].map(s => (
              <button key={s} className="gg-fchip" onClick={() => setQ(s)}>{s}</button>
            ))}
          </div>
        </div>
      ) : !hasAny ? (
        <div className="gg-card" style={{ padding: '48px 28px', textAlign: 'center' }}>
          <BC.Mascot size={96} style={{ margin: '0 auto 12px', display: 'block' }} />
          <h3 className="gg-display gg-h3">No matches for "{q}".</h3>
          <p className="gg-meta" style={{ fontSize: 15, margin: '8px 0 18px' }}>Try a category instead — or browse by room.</p>
          <BC.Btn variant="secondary" onClick={() => nav.go('browse')}>Browse categories</BC.Btn>
        </div>
      ) : (
        <div className="gg-stack" style={{ gap: 40 }}>
          {res.brands.length > 0 && (
            <section>
              <div className="gg-row" style={{ gap: 10, marginBottom: 16 }}>
                <h2 className="gg-display gg-h3">Brands</h2>
                <span className="gg-chip b-solid">{res.brands.length}</span>
              </div>
              <BRes.BrandGrid brands={res.brands} variant={t.cardStyle} />
            </section>
          )}
          {res.categories.length > 0 && (
            <section>
              <h2 className="gg-display gg-h3" style={{ marginBottom: 16 }}>Categories</h2>
              <div className="gg-wrap" style={{ gap: 10 }}>
                {res.categories.map(c => (
                  <button key={c.name} className="gg-fchip" onClick={() => nav.go('category', { cat: c.name })}>
                    {c.name} <span style={{ opacity: 0.5 }}>{c.count}</span>{c.synonym && <span className="gg-meta" style={{ fontSize: 11 }}>↳ match</span>}
                  </button>
                ))}
              </div>
            </section>
          )}
          {res.tags.length > 0 && (
            <section>
              <h2 className="gg-display gg-h3" style={{ marginBottom: 16 }}>Tags</h2>
              <div className="gg-wrap" style={{ gap: 10 }}>
                {res.tags.map(tg => (
                  <span key={tg.name} className="gg-chip b-butter">{tg.name} <span style={{ opacity: 0.55 }}>{tg.count}</span></span>
                ))}
              </div>
            </section>
          )}
        </div>
      )}
    </div>
  );
};

window.GGBrand = { BrandDetailScreen, CategoryScreen, ClusterScreen, SearchScreen };
