// Brands section + Brand detail modal
const { useState: useBState, useEffect: useBEffect } = React;

function Brands({ palette, brand, data, onOpen }) {
  const [filter, setFilter] = useBState("all");
  const filtered = filter === "all" ? data.brands : data.brands.filter(b => b.categories.includes(filter));
  return (
    <section id="brands" className="tiu-section" style={{ background: palette.cream }}>
      <div className="tiu-container">
        <SectionLabel text="Brands we carry" color={brand.blueD} className="reveal-left" />
        <div className="tiu-brands-head">
          <h2 className="tiu-h2 reveal">
            Internationally loved. <span className="script" style={{ color: brand.magenta }}>Locally ready.</span>
          </h2>
          <p className="tiu-lede">Tap a brand to explore its portfolio, featured products, and where to buy.</p>
        </div>

        <div className="tiu-brand-filter">
          <button onClick={() => setFilter("all")} className={filter==="all" ? "is-on" : ""} style={filter==="all"?{background:brand.black,color:"#fff"}:{}}>All brands</button>
          {data.categories.slice(0, 8).map(c => (
            <button key={c.id} onClick={() => setFilter(c.id)} className={filter===c.id ? "is-on" : ""}
              style={filter===c.id?{background:brand.black,color:"#fff"}:{}}>{c.name}</button>
          ))}
        </div>

        <div className="tiu-brand-grid">
          {filtered.map((b) => (
            <BrandCard key={b.id} brand={b} palette={palette} brandC={brand} onOpen={() => onOpen(b)} />
          ))}
          {/* Coming-soon placeholder card so the grid never looks empty */}
          <button className="tiu-brand-card tiu-brand-soon tiu-hit reveal" onClick={() => alert("More brands coming soon ✨")} style={{ borderColor: `${brand.purpleD}40` }}>
            <SparkleCluster s={60} style={{ color: brand.purpleD }} />
            <h4 className="script" style={{ color: brand.purpleD }}>More brands,</h4>
            <h4 className="script" style={{ color: brand.magenta, marginTop: -8 }}>coming soon</h4>
            <p>Our portfolio is growing. Principals — partner with us.</p>
          </button>
        </div>
      </div>
    </section>
  );
}

function BrandCard({ brand, palette, brandC, onOpen }) {
  const accent = palette[brand.accent] || palette.sky;
  return (
    <article className="tiu-brand-card tiu-hit reveal" onClick={onOpen} role="button" tabIndex={0}
      onKeyDown={(e) => (e.key === "Enter" || e.key === " ") && onOpen()}>
      <div className="tiu-brand-hero" style={{ background: accent }}>
        {brand.logo ? (
          <div className="tiu-brand-logo-plate">
            <img src={brand.logo} alt={`${brand.name} logo`} className="tiu-brand-logo-big" />
          </div>
        ) : (
          <div className="tiu-brand-mark-wrap">
            <BrandPlaceholderMark name={brand.name} color={brandC.black} />
          </div>
        )}
      </div>
      <div className="tiu-brand-body">
        <h3>{brand.name}</h3>
        <p>{brand.short}</p>
        <MarketplaceLinks marketplaces={brand.marketplaces} palette={palette} brandC={brandC} compact
          only={["shopee", "lazada", "tiktokShop", "website"]} />
        <span className="tiu-brand-more">View brand <span aria-hidden>→</span></span>
      </div>
    </article>
  );
}

function BrandPlaceholderMark({ name, color }) {
  // Original placeholder wordmark — NOT the real brand logo
  const initials = name.replace(/[^A-Za-z]/g, "").slice(0, 1).toUpperCase();
  return (
    <div style={{
      display: "inline-flex", flexDirection: "column", alignItems: "center", gap: 6,
      padding: "18px 26px", background: "rgba(255,255,255,0.9)", borderRadius: 16,
      boxShadow: "0 10px 30px rgba(0,0,0,0.08)",
    }}>
      <div style={{
        width: 44, height: 44, borderRadius: 999,
        background: color, color: "#fff",
        display: "flex", alignItems: "center", justifyContent: "center",
        fontFamily: "'DM Sans', sans-serif", fontWeight: 700, fontSize: 22, letterSpacing: "0.02em",
      }}>{initials}</div>
      <span style={{
        fontFamily: "'Poppins', sans-serif",
        fontSize: 10, letterSpacing: "0.18em", textTransform: "uppercase",
        color: color, opacity: 0.8,
      }}>placeholder · {name.toLowerCase()}</span>
    </div>
  );
}

const MARKETPLACE_ITEMS = [
  { key: "shopee",     label: "Shopee",      img: "logos/SHOPEE.png" },
  { key: "lazada",     label: "Lazada",      img: "logos/LAZADA.png" },
  { key: "tiktokShop", label: "TikTok Shop", img: "logos/TIKTOKSHOP.png" },
  { key: "facebook",   label: "Facebook",    img: "logos/FB.png" },
  { key: "instagram",  label: "Instagram",   img: "logos/INSTAGRAM.png" },
  { key: "tiktok",     label: "TikTok",      img: "logos/TIKTOK.png" },
  { key: "website",    label: "Website",     img: null, glyph: "↗" },
];

function MarketplaceLinks({ marketplaces, palette, brandC, compact, only }) {
  const items = MARKETPLACE_ITEMS
    .filter(x => x.key in marketplaces)
    .filter(x => !only || only.includes(x.key))
    .map(x => x.key === "website" ? { ...x, color: brandC.magenta } : x);
  return (
    <div className="tiu-mp" data-compact={compact || undefined}>
      {items.map(i => {
        const href = marketplaces[i.key];
        const glyph = i.img
          ? <span className="tiu-mp-glyph" style={{ background: "#fff", display: "inline-flex", alignItems: "center", justifyContent: "center", borderRadius: "50%" }}>
              <img src={i.img} alt={i.label} style={{ width: 22, height: 22, objectFit: "contain", display: "block" }} />
            </span>
          : <span className="tiu-mp-glyph" style={{ background: i.color, color: "#fff" }}>{i.glyph}</span>;
        return href ? (
          <a key={i.key} href={href} onClick={(e) => e.stopPropagation()} className="tiu-mp-chip tiu-hit">
            {glyph}
            <span className="tiu-mp-label">{i.label}</span>
          </a>
        ) : (
          <span key={i.key} className="tiu-mp-chip tiu-mp-chip-soon" title="Coming soon" onClick={(e) => e.stopPropagation()}>
            {glyph}
            <span className="tiu-mp-label">{i.label}</span>
          </span>
        );
      })}
    </div>
  );
}

function BrandModal({ brand, palette, brandC, data, onClose }) {
  useBEffect(() => {
    if (!brand) return;
    const onKey = (e) => e.key === "Escape" && onClose();
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {
      window.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [brand, onClose]);

  if (!brand) return null;
  const accent = palette[brand.accent] || palette.sky;
  const catNames = brand.categories.map(id => data.categories.find(c => c.id === id)?.name).filter(Boolean);

  return (
    <div className="tiu-modal-backdrop" onClick={onClose}>
      <div className="tiu-modal" onClick={(e) => e.stopPropagation()} role="dialog" aria-label={`${brand.name} details`}>
        <button className="tiu-modal-close tiu-hit" onClick={onClose} aria-label="Close">×</button>
        <div className="tiu-modal-hero" style={{ background: accent }}>
          {brand.logo ? (
            <div className="tiu-brand-logo-plate">
              <img src={brand.logo} alt={`${brand.name} logo`} className="tiu-brand-logo-big" />
            </div>
          ) : (
            <BrandPlaceholderMark name={brand.name} color={brandC.black} />
          )}
        </div>
        <div className="tiu-modal-body">
          <h2 className="tiu-h2" style={{ marginBottom: 8 }}>{brand.name}</h2>
          <p className="tiu-lede" style={{ marginBottom: 24 }}>{brand.long}</p>

          <div className="tiu-modal-row">
            <h5>Categories</h5>
            <div className="tiu-tag-row">
              {catNames.map(n => (<span key={n} className="tiu-tag">{n}</span>))}
            </div>
          </div>

          <div className="tiu-modal-row">
            <h5>Where to buy</h5>
            <MarketplaceLinks marketplaces={brand.marketplaces} palette={palette} brandC={brandC}
              only={["shopee", "lazada", "tiktokShop"]} />
          </div>

          <div className="tiu-modal-row">
            <h5>Brand socials</h5>
            <MarketplaceLinks marketplaces={brand.marketplaces} palette={palette} brandC={brandC}
              only={["facebook", "instagram", "tiktok", "website"]} />
          </div>

        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Brands, BrandCard, BrandModal, MarketplaceLinks });
