/* ============================================================
   lookslikeagoodman — Homepage (2 hero concepts + sections)
   ============================================================ */

/* ---------------- CAROUSEL HERO ---------------- */
function HeroCarousel({ onNav }) {
  const DURATION = 4800;
  const SLIDES = [
    { imgLabel: "AGBADA · TRADITIONAL", eyebrow: "Traditional & Ceremonial",
      headline: "Looks like\na good man.", sub: "Full traditional agbada, coral beadwork and ceremonial dress.",
      cta: "Shop Agbada", ctaFn: () => onNav("shop", { cat: "Agbada" }), accent: "var(--accent-bright)" },
    { imgLabel: "KAFTAN · SIGNATURE", eyebrow: "Signature Kaftans",
      headline: "Cut with\npurpose.", sub: "Embroidered kaftans and cape-sleeve silhouettes.",
      cta: "Shop Kaftans", ctaFn: () => onNav("shop", { cat: "Kaftan" }), accent: "#e8c4c4" },
    { imgLabel: "SETS · CONTEMPORARY", eyebrow: "Contemporary Sets",
      headline: "Studio\nready.", sub: "Relaxed tops and trouser sets, made to be worn every day.",
      cta: "Shop Sets", ctaFn: () => onNav("shop", { cat: "Sets" }), accent: "var(--accent-bright)" },
    { imgLabel: "OCCASION · FAMILY", eyebrow: "Occasion & Family",
      headline: "Dressed as\none.", sub: "Coordinated aso-ebi looks for the moments worth remembering.",
      cta: "Shop Occasion", ctaFn: () => onNav("shop", { cat: "Occasion" }), accent: "#aebfce" },
  ];

  const [cur, setCur] = useState(0);
  const [progKey, setProgKey] = useState(0);
  const pausedRef = useRef(false);
  const heroRef = useRef(null);

  useEffect(() => {
    const t = setInterval(() => { if (!pausedRef.current) { setCur(c => (c + 1) % SLIDES.length); setProgKey(k => k + 1); } }, DURATION);
    return () => clearInterval(t);
  }, []);

  const go = (n) => { setCur(((n % SLIDES.length) + SLIDES.length) % SLIDES.length); setProgKey(k => k + 1); };
  const slide = SLIDES[cur];

  return (
    <section ref={heroRef} className="hero hero-carousel"
      onMouseEnter={() => { pausedRef.current = true; }} onMouseLeave={() => { pausedRef.current = false; }}>
      <div className="hc-bgs" aria-hidden="true">
        {SLIDES.map((s, i) => {
          const src = (window.RB_IMGS || {})[s.imgLabel] || "";
          return <div key={i} className={"hc-bg" + (i === cur ? " active" : "")} style={{ backgroundImage: src ? `url(${src})` : "none" }} />;
        })}
      </div>
      <div className="hc-overlay" aria-hidden="true" />
      <div className="hc-bottom-fade" aria-hidden="true" />
      <div className="hc-progress-track" aria-hidden="true">
        <div key={progKey} className="hc-progress-fill" style={{ "--hc-dur": DURATION + "ms", "--hc-accent": slide.accent }} />
      </div>
      <div className="wrap hc-content" key={cur}>
        <Eyebrow style={{ color: slide.accent, marginBottom: 18 }}>{slide.eyebrow}</Eyebrow>
        <h1 className="display hc-headline" style={{ whiteSpace: "pre-line" }}>{slide.headline}</h1>
        <p className="lede hc-sub">{slide.sub}</p>
        <div className="hero-cta" style={{ marginTop: 38 }}>
          <Btn onClick={slide.ctaFn}>{slide.cta}</Btn>
          <Btn variant="ghost" arrow={false} className="on-dark" onClick={() => onNav("custom", {})}>Enquire</Btn>
        </div>
      </div>
      <button className="hc-arrow hc-prev" onClick={() => go(cur - 1)} aria-label="Previous slide">
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M19 12H5M11 6l-6 6 6 6"/></svg>
      </button>
      <button className="hc-arrow hc-next" onClick={() => go(cur + 1)} aria-label="Next slide">
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
      </button>
      <div className="hc-dots" role="tablist">
        {SLIDES.map((_, i) => <button key={i} role="tab" aria-label={"Slide " + (i + 1)} aria-selected={i === cur}
          className={"hc-dot" + (i === cur ? " active" : "")} style={{ "--dot-accent": slide.accent }} onClick={() => go(i)} />)}
      </div>
      <div className="hc-counter" aria-hidden="true">
        <span className="mono">{String(cur + 1).padStart(2, "0")}</span>
        <span style={{ opacity: 0.3 }}>/</span>
        <span className="mono" style={{ opacity: 0.4 }}>{String(SLIDES.length).padStart(2, "0")}</span>
      </div>
    </section>
  );
}

function Hero(props) {
  const map = { carousel: HeroCarousel, collage: HeroCollage };
  const Cmp = map[props.layout] || HeroCollage;
  return <Cmp {...props} />;
}

/* ---------------- TRUST BAR ---------------- */
function TrustBar() {
  const items = [
    { icon: "scissors", t: "Made to measure", s: "Every piece can be tailored to you" },
    { icon: "ruler", t: "Perfect fit", s: "Size guide & fit finder" },
    { icon: "ig", t: "Enquire on Instagram", s: (window.BRAND && window.BRAND.igHandle) || "@lookslikeagoodman" },
    { icon: "mail", t: "Enquire on-site", s: "Add pieces & send an enquiry" },
  ];
  return (
    <div className="trustbar">
      <div className="wrap trustbar-inner">
        {items.map((it) => (
          <div className="trust-item" key={it.t}>
            <Icon name={it.icon} size={22} stroke={1.4} />
            <div><span className="trust-t">{it.t}</span><span className="trust-s">{it.s}</span></div>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ---------------- CATEGORY STRIP ---------------- */
function CategoryStrip({ onNav }) {
  const cats = [
    { name: "Agbada", disp: "Agbada", label: "AGBADA", n: "01" },
    { name: "Kaftan", disp: "Kaftans", label: "KAFTAN", n: "02" },
    { name: "Sets", disp: "Sets", label: "SETS", n: "03" },
    { name: "Occasion", disp: "Occasion", label: "OCCASION", n: "04" },
  ];
  return (
    <section className="section-pad-sm">
      <div className="wrap-wide">
        <Reveal className="section-head" style={{ marginBottom: 40 }}>
          <h2 className="serif">Shop by category</h2>
          <button className="link-arrow" onClick={() => onNav("shop", {})}>All products</button>
        </Reveal>
        <div className="cat-strip">
          {cats.map((c, i) => (
            <Reveal key={c.name} delay={(i % 4) + 1} className="cat-card zoomable">
              <button className="cat-card-btn" onClick={() => onNav("shop", { cat: c.name })}>
                <Ph label={c.label + " · SHOP"} ratio="portrait" />
                <div className="cat-card-cap"><span className="mono">{c.n}</span><span className="serif">{c.disp}</span></div>
              </button>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------------- FEATURED PRODUCTS ---------------- */
function FeaturedRow({ title, eyebrow, products, onNav, link }) {
  const { addToCart, toggleWish, wishlist } = useContext(RBCtx);
  return (
    <section className="section-pad">
      <div className="wrap-wide">
        <Reveal className="section-head" style={{ marginBottom: 44 }}>
          <div><Eyebrow>{eyebrow}</Eyebrow><h2 className="serif" style={{ marginTop: 14 }}>{title}</h2></div>
          <button className="link-arrow" onClick={() => onNav("shop", link || {})}>View all</button>
        </Reveal>
        <div className="product-grid">
          {products.map((p, i) => (
            <Reveal key={p.id} delay={(i % 4) + 1}>
              <ProductCard p={p} onNav={onNav} onAdd={addToCart} wished={wishlist.includes(p.id)} onWish={toggleWish} />
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------------- STORY ---------------- */
function StorySection({ onNav }) {
  return (
    <section className="section-pad story-sec">
      <div className="wrap-wide story-grid">
        <Reveal className="story-media zoomable"><Ph label="ATELIER · STUDIO" ratio="portrait" /></Reveal>
        <div className="story-body">
          <Reveal><Eyebrow line>Our Story</Eyebrow></Reveal>
          <Reveal delay={1}><h2 className="serif story-h">Looks like a good man.</h2></Reveal>
          <Reveal delay={2}>
            <p className="lede" style={{ marginBottom: 22 }}>{(window.BRAND?.story.lede)}</p>
            <p style={{ color: "var(--ink-soft)", marginBottom: 30 }}>{(window.BRAND?.story.body)} {(window.BRAND?.story.craftLine)}</p>
          </Reveal>
          <Reveal delay={3} className="row" style={{ gap: 18, flexWrap: "wrap" }}><Btn onClick={() => onNav("about", {})}>Read our story</Btn></Reveal>
        </div>
      </div>
    </section>
  );
}

/* ---------------- COLLECTIONS STRIP ---------------- */
function OccasionSection({ onNav }) {
  return (
    <section className="section-pad occ-sec">
      <div className="wrap-wide">
        <Reveal className="section-head center-head">
          <div className="center" style={{ width: "100%" }}>
            <Eyebrow>Curated edits</Eyebrow>
            <h2 className="serif" style={{ margin: "14px auto 0", maxWidth: "none" }}>Shop by collection</h2>
          </div>
        </Reveal>
        <div className="occ-grid">
          {RB.COLLECTIONS.map((c, i) => (
            <Reveal key={c.id} delay={(i % 4) + 1} className="occ-card zoomable">
              <button className="occ-card-btn" onClick={() => onNav("shop", { cat: c.catFilter })}>
                <Ph label={c.label} ratio={i % 2 === 0 ? "tall" : "portrait"} />
                <div className="occ-overlay" />
                <div className="occ-cap">
                  <span className="mono">{c.tag}</span>
                  <span className="serif occ-title">{c.title}</span>
                  <span className="occ-blurb">{c.blurb}</span>
                  <span className="link-arrow on-img">Explore</span>
                </div>
              </button>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------------- BESPOKE CTA ---------------- */
function BespokeBand({ onNav }) {
  return (
    <section className="bespoke-band">
      <div className="wrap-wide bespoke-grid">
        <div className="bespoke-media zoomable"><Ph label="BESPOKE · ENQUIRE" ratio="square" /></div>
        <div className="bespoke-body">
          <Eyebrow line>Bespoke &amp; Enquiries</Eyebrow>
          <h2 className="serif bespoke-h">Commissioned for you, down to the stitch.</h2>
          <p className="lede" style={{ marginBottom: 26 }}>
            Interested in a piece, or want it made to your measurements? Send an enquiry on-site or DM us on Instagram
            — we'll follow up with availability and pricing.
          </p>
          <div className="hero-cta">
            <Btn onClick={() => onNav("custom", {})}>Enquire</Btn>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------------- COMMUNITY / EDIT STRIP ---------------- */
function CommunityStrip() {
  const looks = ["AGBADA · TRADITIONAL", "KAFTAN · SIGNATURE", "SETS · CONTEMPORARY", "OCCASION · FAMILY", "SETS · STUDIO", "EDITORIAL · HERITAGE"];
  return (
    <section className="insta-sec">
      <div className="center" style={{ marginBottom: 32 }}>
        <Eyebrow>{(window.BRAND && window.BRAND.igHandle) || "@lookslikeagoodman"}</Eyebrow>
        <h2 className="serif" style={{ fontSize: "clamp(28px,3.4vw,42px)", fontWeight: 500, marginTop: 10 }}>Follow along</h2>
      </div>
      <div className="insta-row">
        {looks.map((label, i) => (
          <a key={i} className="insta-cell zoomable" href={(window.BRAND && window.BRAND.igUrl) || "#"} target="_blank" rel="noopener" aria-label="Instagram">
            <Ph label={label} ratio="square" />
            <span className="insta-ic"><Icon name="ig" size={20} /></span>
          </a>
        ))}
      </div>
    </section>
  );
}

/* ---------------- PRODUCT CARD ---------------- */
function ProductCard({ p, onNav, onAdd, wished, onWish }) {
  return (
    <article className="pcard zoomable" onClick={() => onNav("product", { id: p.id })}>
      <div className="pcard-media">
        <button className={"wish" + (wished ? " active" : "")} onClick={(e) => { e.stopPropagation(); onWish(p.id); }} aria-label="Wishlist">
          <Icon name={wished ? "star-f" : "heart"} size={17} />
        </button>
        <Ph label={p.label} ratio="portrait" />
        <button className="quick" onClick={(e) => { e.stopPropagation(); onAdd(p, { size: p.sizes[1] || p.sizes[0], color: p.colors[0].name }); }}>
          + Enquire
        </button>
      </div>
      <div className="pcard-body">
        <span className="pcard-cat">{p.cat} · {p.gender}</span>
        <span className="pcard-name">{p.name}</span>
        <span className="pcard-price"><Price /></span>
        <div className="swatches">{p.colors.slice(0, 4).map((c) => <span key={c.name} className="swatch" style={{ background: c.hex }} title={c.name} />)}</div>
      </div>
    </article>
  );
}

/* ---------------- HOME PAGE ---------------- */
function HomePage({ onNav, tweaks }) {
  const featured = RB.PRODUCTS.slice(0, 4);
  const more = RB.PRODUCTS.slice(4, 8);
  return (
    <div className="fade-page">
      <Hero layout={tweaks.heroLayout} headline={tweaks.heroHeadline} sub={tweaks.heroSub} onNav={onNav} />
      <TrustBar />
      <CategoryStrip onNav={onNav} />
      <FeaturedRow eyebrow="The collection" title="Shop the edit" products={featured} onNav={onNav} />
      <StorySection onNav={onNav} />
      <OccasionSection onNav={onNav} />
      <FeaturedRow eyebrow="More looks" title="Also from the collection" products={more} onNav={onNav} />
      <BespokeBand onNav={onNav} />
      <CommunityStrip />
    </div>
  );
}

Object.assign(window, { HomePage, ProductCard, Hero, HeroCarousel });
