// screens-brands.jsx — the brand directory and the brand page, both rendered
// from the `brands` table.
//
// There is no per-brand code: a row is a page. Adding a brand in Studio →
// Brands publishes /brands/<slug> immediately, and the outfits section fills
// itself in as creators publish looks featuring that brand's products.
//
// Matching is by name, on an item's brand and store, whole words only — see
// mb_brand_matches() in supabase/schema.sql, mirrored by MBBrands.matchesItem
// so this page and the database agree about what "features this brand" means.

const { useState: useStateBr, useEffect: useEffectBr, useMemo: useMemoBr } = React;

// ─── Brands index ──────────────────────────────────────────────────────────
function BrandsScreen({ go }) {
  const [brands, setBrands] = useStateBr([]);
  const [loading, setLoading] = useStateBr(true);
  const [error, setError] = useStateBr(null);

  useEffectBr(() => {
    let cancelled = false;
    (async () => {
      const res = await window.MBBrands.list();
      if (cancelled) return;
      if (res.error) setError(res.error); else setBrands(res.brands);
      setLoading(false);
    })();
    return () => { cancelled = true; };
  }, []);

  return (
    <div>
      <section style={{ padding: '64px 40px 32px' }}>
        <div style={{ maxWidth: 1280, marginInline: 'auto' }}>
          <div style={{ fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase', color: '#8a8580' }}>Brands</div>
          <h1 style={{ margin: '10px 0 16px', fontSize: 'clamp(40px, 6vw, 64px)', fontWeight: 400, letterSpacing: '-0.03em' }}>The houses behind the fits.</h1>
          <p style={{ fontSize: 16, color: '#3a3a36', maxWidth: '56ch', lineHeight: 1.55 }}>
            Every product on modaBoard traces back to a brand with a point of view. Read the story, then shop the outfits our creators built around them.
          </p>
        </div>
      </section>

      <section style={{ padding: '24px 40px 40px' }}>
        <div style={{ maxWidth: 1280, marginInline: 'auto' }}>
          {loading && <div style={{ padding: '40px 0', color: '#8a8580', fontSize: 13 }}>Loading brands…</div>}

          {!loading && error && (
            <div style={{
              padding: '40px 28px', borderRadius: 14, textAlign: 'center',
              background: '#fff', border: '1px dashed rgba(20,20,18,0.16)', color: '#a8331a', fontSize: 14,
            }}>{error}</div>
          )}

          {!loading && !error && brands.length === 0 && (
            <div style={{
              padding: '64px 32px', borderRadius: 16, textAlign: 'center',
              background: '#fff', border: '1px dashed rgba(20,20,18,0.16)',
            }}>
              <h2 style={{ margin: 0, fontSize: 26, fontWeight: 400, letterSpacing: '-0.02em' }}>No brands yet</h2>
              <p style={{ marginTop: 12, color: '#5a5a54', fontSize: 14.5, lineHeight: 1.6 }}>
                Brands are added in Studio, and each one gets its own page here.
              </p>
            </div>
          )}

          {!loading && !error && brands.length > 0 && (
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(340px, 1fr))', gap: 22 }}>
              {brands.map(b => <BrandCard key={b.slug} brand={b} onOpen={() => go({ name: 'brand', slug: b.slug })}/>)}
            </div>
          )}
        </div>
      </section>
      <Footer/>
    </div>
  );
}

function BrandCard({ brand, onOpen }) {
  const [hover, setHover] = useStateBr(false);
  return (
    <div data-brand={brand.slug} onClick={onOpen}
      onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{
        cursor: 'pointer', borderRadius: 16, overflow: 'hidden',
        background: '#FAFAF7', border: '1px solid rgba(20,20,18,0.06)',
        display: 'flex', flexDirection: 'column',
        transition: 'box-shadow .25s ease, transform .25s ease',
        boxShadow: hover ? '0 24px 60px -24px rgba(20,20,18,0.16)' : 'none',
        transform: hover ? 'translateY(-2px)' : 'none',
      }}>
      <BrandHero brand={brand} ratio="16 / 10" fontSize={40}/>
      <div style={{ padding: 22, display: 'flex', flexDirection: 'column', gap: 10, flex: 1 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 12 }}>
          <h2 style={{ margin: 0, fontSize: 26, fontWeight: 400, letterSpacing: '-0.02em' }}>{brand.name}</h2>
          {brand.estYear && <span style={{ fontSize: 11, color: '#8a8580', whiteSpace: 'nowrap' }}>Est. {brand.estYear}</span>}
        </div>
        {brand.location && <div style={{ fontSize: 12, color: '#8a8580' }}>{brand.location}</div>}
        {brand.story && (
          <p style={{ margin: '4px 0 0', fontSize: 13.5, color: '#3a3a36', lineHeight: 1.55, flex: 1 }}>
            {firstSentences(brand.story, 2)}
          </p>
        )}
        <div style={{ marginTop: 6, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <span style={{ fontSize: 11.5, letterSpacing: '0.06em', color: '#8a8580' }}>
            {brand.outfitCount} {brand.outfitCount === 1 ? 'outfit' : 'outfits'}
          </span>
          <span style={{ fontSize: 11.5, letterSpacing: '0.14em', textTransform: 'uppercase', fontWeight: 500, color: '#1a1a18' }}>Read more →</span>
        </div>
      </div>
    </div>
  );
}

// The brand's image, or its name set as a wordmark when there isn't one.
//
// Brand shots arrive the way product shots do — the piece on a plain studio
// ground — so they get the same treatment: the stored cutout when an admin has
// made one, and otherwise the cutout made here and now, exactly as
// ProductImage does it. The card ground shows through either way, so a brand
// image never sits in a grey box of its own.
//
// Contained rather than cropped: cover would cut the product in half.
function BrandHero({ brand, ratio, fontSize, pad = '10%' }) {
  const stored = brand.heroImageTransparentUrl || null;
  const original = brand.heroImageUrl || null;
  const [broken, setBroken] = useStateBr(false);
  const [src, setSrc] = useStateBr(stored || original);
  // `cut` is what licenses normal blending. Until the background is actually
  // gone, multiply keeps a white ground from printing as a white rectangle.
  const [cut, setCut] = useStateBr(!!stored);

  useEffectBr(() => {
    setBroken(false);
    setSrc(stored || original);
    setCut(!!stored);
    if (stored || !original || !window.DripcheckBG) return;
    let alive = true;
    window.DripcheckBG.removeBackground(original)
      .then(png => { if (alive && png) { setSrc(png); setCut(true); } })
      .catch(() => { /* not a uniform ground — the original still reads fine */ });
    return () => { alive = false; };
  }, [stored, original]);

  const showing = !broken && src ? src : null;
  return (
    <div style={{
      position: 'relative', aspectRatio: ratio, background: '#FAFAF7',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      borderBottom: '1px solid rgba(20,20,18,0.05)', overflow: 'hidden',
      padding: showing ? pad : 0, boxSizing: 'border-box',
    }}>
      {showing
        ? <img src={showing} alt={brand.name} loading="lazy" onError={() => setBroken(true)}
               data-cut={cut ? 'yes' : 'no'}
               style={{
                 maxWidth: '100%', maxHeight: '100%', objectFit: 'contain', display: 'block',
                 mixBlendMode: cut ? 'normal' : 'multiply',
                 // A drop-shadow traces the alpha channel, so on an un-cut
                 // image it would outline the photo's rectangle — the very
                 // box this change exists to get rid of.
                 filter: cut ? 'drop-shadow(0 8px 18px rgba(20,20,18,0.10))' : 'none',
               }}/>
        : <div style={{ fontFamily: "'Instrument Serif',serif", fontStyle: 'italic', fontSize, color: '#c9c5bd' }}>{brand.name}</div>}
      {brand.category && (
        <div style={{
          position: 'absolute', top: 14, left: 14, fontSize: 10, letterSpacing: '0.16em',
          textTransform: 'uppercase', color: '#8a8580',
        }}>{brand.category}</div>
      )}
    </div>
  );
}

function firstSentences(text, n) {
  const parts = String(text || '').split('. ');
  return parts.length <= n ? text : parts.slice(0, n).join('. ') + '.';
}

// ─── Brand page ────────────────────────────────────────────────────────────
function BrandDetailScreen({ slug, go }) {
  const [brand, setBrand] = useStateBr(null);
  const [outfits, setOutfits] = useStateBr([]);
  const [loading, setLoading] = useStateBr(true);
  const [error, setError] = useStateBr(null);

  useEffectBr(() => {
    let cancelled = false;
    (async () => {
      setLoading(true);
      setError(null);
      const res = await window.MBBrands.get(slug);
      if (cancelled) return;
      if (res.error) { setError(res.error); setLoading(false); return; }
      setBrand(res.brand);
      if (!res.brand) { setOutfits([]); setLoading(false); return; }
      const list = await window.MBBrands.outfits(slug);
      if (cancelled) return;
      if (list.error) setError(list.error); else setOutfits(list.outfits);
      setLoading(false);
    })();
    return () => { cancelled = true; };
  }, [slug]);

  useEffectBr(() => {
    if (brand) document.title = `${brand.name} — Outfits & Products | modaBoard`;
    return () => { document.title = 'modaBoard — Shoppable Outfit Boards for Creators'; };
  }, [brand]);

  // The brand's own pieces, taken from the outfits that feature it. Same rule
  // the database used to pick those outfits.
  const products = useMemoBr(() => {
    if (!brand) return [];
    const seen = new Map();
    outfits.forEach(o => (o.items || []).forEach(it => {
      if (it && it.image && window.MBBrands.matchesItem(brand.name, it) && !seen.has(it.name || it.id)) {
        seen.set(it.name || it.id, it);
      }
    }));
    return [...seen.values()];
  }, [outfits, brand]);

  if (loading) {
    return <div style={{ padding: '96px 40px', textAlign: 'center', color: '#8a8580', fontSize: 13 }}>Loading brand…</div>;
  }

  if (error || !brand) {
    return (
      <div style={{ padding: '72px 28px' }}>
        <NotFoundCard
          title={error ? 'Something went wrong' : 'Brand not found'}
          body={error || <>There’s no brand at this address. It may have been renamed or removed.</>}
          go={go}
        />
        <Footer/>
      </div>
    );
  }

  return (
    <div>
      <section style={{ padding: '32px 40px 8px' }}>
        <div style={{ maxWidth: 1280, marginInline: 'auto' }}>
          <button onClick={() => go({ name: 'brands' })} style={linkBtn}>← All brands</button>
        </div>
      </section>

      {/* Hero */}
      <section style={{ padding: '16px 40px 40px' }}>
        <div style={{ maxWidth: 1280, marginInline: 'auto', display: 'grid', gridTemplateColumns: 'minmax(0, 1.15fr) minmax(0, 1fr)', gap: 40, alignItems: 'center' }} className="dc-brand-hero">
          <div>
            <div style={{ fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase', color: '#8a8580' }}>
              {[brand.category, brand.estYear && 'Est. ' + brand.estYear].filter(Boolean).join(' · ')}
            </div>
            <h1 style={{ margin: '12px 0 0', fontSize: 'clamp(48px, 7vw, 88px)', lineHeight: 0.95, letterSpacing: '-0.04em', fontWeight: 400 }}>{brand.name}</h1>
            {brand.location && (
              <div style={{ marginTop: 14, fontFamily: "'Instrument Serif',serif", fontStyle: 'italic', fontSize: 18, color: '#5a5a54' }}>{brand.location}</div>
            )}
            {brand.story && <p style={{ marginTop: 22, fontSize: 16.5, color: '#2a2a26', lineHeight: 1.6, maxWidth: '52ch' }}>{brand.story}</p>}
            {brand.platformNote && <p style={{ marginTop: 16, fontSize: 14, color: '#5a5a54', lineHeight: 1.6, maxWidth: '52ch' }}>{brand.platformNote}</p>}
            {brand.tags.length > 0 && (
              <div style={{ marginTop: 20, display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                {brand.tags.map(t => (
                  <span key={t} style={{ fontSize: 11, letterSpacing: '0.04em', padding: '6px 12px', borderRadius: 999, background: '#F2EFE7', color: '#3a3a36' }}>{t}</span>
                ))}
              </div>
            )}
          </div>
          <div style={{ borderRadius: 18, overflow: 'hidden', border: '1px solid rgba(20,20,18,0.06)', boxShadow: '0 30px 80px -40px rgba(20,20,18,0.2)' }}>
            <BrandHero brand={brand} ratio="4 / 5" fontSize={52} pad="16%"/>
          </div>
        </div>
      </section>

      {/* Stat strip */}
      <section style={{ padding: '0 40px' }}>
        <div style={{ maxWidth: 1280, marginInline: 'auto', display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 0, borderTop: '1px solid rgba(20,20,18,0.08)', borderBottom: '1px solid rgba(20,20,18,0.08)' }}>
          <Stat label="Outfits featuring" value={outfits.length}/>
          <Stat label="Products on modaBoard" value={products.length} border/>
          <Stat label="Founded" value={brand.estYear || '—'}/>
        </div>
      </section>

      {/* Pieces from this brand */}
      {products.length > 0 && (
        <section style={{ padding: '44px 40px 8px' }}>
          <div style={{ maxWidth: 1280, marginInline: 'auto' }}>
            <h2 style={{ margin: '0 0 22px', fontSize: 28, fontWeight: 400, letterSpacing: '-0.02em' }}>Pieces on the platform</h2>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(180px, 1fr))', gap: 16 }}>
              {products.map((p, i) => (
                <div key={i} style={{ borderRadius: 14, overflow: 'hidden', background: '#FAFAF7', border: '1px solid rgba(20,20,18,0.06)' }}>
                  <div style={{ aspectRatio: '1 / 1', background: '#FAFAF7', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '14%' }}>
                    <ProductImage item={p}/>
                  </div>
                  <div style={{ padding: '12px 14px' }}>
                    <div style={{ fontSize: 10.5, letterSpacing: '0.1em', textTransform: 'uppercase', color: '#8a8580' }}>{p.brand}</div>
                    <div style={{ fontSize: 13, marginTop: 3, lineHeight: 1.3 }}>{p.name}</div>
                    {p.price ? <div style={{ fontSize: 12, color: '#5a5a54', marginTop: 4 }}>{MBMoney.format(p.price, p.currency)}{p.store ? ' · ' + p.store : ''}</div> : null}
                  </div>
                </div>
              ))}
            </div>
          </div>
        </section>
      )}

      {/* Outfits featuring the brand — real published boards, each linking to
          its own public page so a visitor can shop the pieces. */}
      <section style={{ padding: '44px 40px 40px' }}>
        <div style={{ maxWidth: 1280, marginInline: 'auto' }}>
          <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 22 }}>
            <h2 style={{ margin: 0, fontSize: 28, fontWeight: 400, letterSpacing: '-0.02em' }}>Outfits featuring {brand.name}</h2>
            <button onClick={() => go({ name: 'creators' })} style={linkBtn}>All creators →</button>
          </div>
          {outfits.length > 0 ? (
            <div style={{ display: 'grid', gap: 24, gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))' }} className="dc-brand-grid">
              {outfits.map(o => (
                <PublishedOutfitCard
                  key={o.id}
                  outfit={o}
                  onOpen={() => go({ name: 'share', username: o.username, slug: o.slug })}
                />
              ))}
            </div>
          ) : (
            <div style={{
              padding: '56px 32px', textAlign: 'center', borderRadius: 16,
              background: '#fff', border: '1px dashed rgba(20,20,18,0.16)',
            }}>
              <div style={{ fontFamily: "'Instrument Serif',serif", fontStyle: 'italic', fontSize: 22, color: '#5a5a54' }}>
                No published outfits feature {brand.name} yet.
              </div>
              <p style={{ marginTop: 10, fontSize: 14, color: '#8a8580', lineHeight: 1.6 }}>
                Build a look with one of their pieces and publish it — it lands here.
              </p>
              <button onClick={() => go({ name: 'dashboard' })} style={{
                appearance: 'none', border: 'none', background: '#1a1a18', color: '#FAFAF7',
                fontSize: 11.5, padding: '12px 20px', letterSpacing: '0.14em', marginTop: 20,
                textTransform: 'uppercase', fontWeight: 500, borderRadius: 999,
                cursor: 'pointer', fontFamily: 'inherit',
              }}>Create an outfit</button>
            </div>
          )}
        </div>
      </section>
      <Footer/>
    </div>
  );
}

function Stat({ label, value, border }) {
  return (
    <div style={{ padding: '24px 20px', textAlign: 'center', borderLeft: border ? '1px solid rgba(20,20,18,0.08)' : 'none', borderRight: border ? '1px solid rgba(20,20,18,0.08)' : 'none' }}>
      <div style={{ fontSize: 34, fontWeight: 400, letterSpacing: '-0.02em', fontVariantNumeric: 'tabular-nums' }}>{value}</div>
      <div style={{ marginTop: 6, fontSize: 11, letterSpacing: '0.16em', textTransform: 'uppercase', color: '#8a8580' }}>{label}</div>
    </div>
  );
}

Object.assign(window, { BrandsScreen, BrandDetailScreen, BrandCard, BrandHero });
