/* global React */
const { useState, useEffect, useRef } = React;

// ───────────────────────────────────────────────────────────────
// Shared bits: nav, footer, instagram strip, primitives
// ───────────────────────────────────────────────────────────────

const NAV_ITEMS = [
  { label: "Lookbook", href: "Lookbook.html" },
  { label: "Visit",    href: "Visit.html" },
];

// Pinned photos (Susan herself — never in the feed) plus a few studio shots
// referenced by name from the Heritage and Gallery layouts.
const PINNED_PHOTOS = {
  susanKente:      { src: "images/susan-kente-portrait.jpg", alt: "Susan in kente headwrap, at her sewing machine",  pos: "face" },
  susanRedchair:   { src: "images/susan-redchair.jpg",        alt: "Susan in adinkra-print dress with kente sash",     pos: "face" },
  susanCambridge:  { src: "images/susan-cambridge.jpg",       alt: "Susan in white blazer over kente top, Cambridge",  pos: "face" },
  susanGraduation: { src: "images/susan-graduation.jpg",      alt: "Susan in academic robes with kente stole",         pos: "face" },
  susanBlackGown:  { src: "images/susan-black-gown.jpg",      alt: "Susan in a beaded black evening gown",             pos: "face" },
  // Studio shots used as static visuals in alternate layouts
  shopFive:        { src: "images/shop-mannequins-five.jpg",  alt: "Five gowns lined up in the studio" },
  shopRow:         { src: "images/shop-mannequins-row.jpg",   alt: "Four mannequins in the Tooting studio" },
  // Garments referenced by name from heritage / gallery (legacy)
  customerRedLace:    { src: "images/customer-red-lace.jpg",            alt: "Embroidered velvet, silver shoulder wrap" },
  pieceFloralMermaid: { src: "images/garment-floral-mermaid.jpg",       alt: "Floral mermaid gown" },
  pieceYellowStrap:   { src: "images/garment-yellow-strapless.jpg",     alt: "Yellow striped strapless" },
  pieceDashiki:       { src: "images/garment-dashiki-black.jpg",        alt: "Black dashiki maxi" },
  piecePinkTeal:      { src: "images/garment-pink-teal-peplum.jpg",     alt: "Pink and teal peplum" },
  piecePinkTealPat:   { src: "images/garment-pink-teal-pattern.jpg",    alt: "Pink and teal pattern" },
  pieceSilverBrocade: { src: "images/garment-silver-brocade.jpg",       alt: "Silver brocade gown" },
  piecePinkSequin:    { src: "images/garment-pink-sequin.jpg",          alt: "Pink sequin under floral wrap" },
  pieceCreamRuffle:   { src: "images/garment-cream-ruffle.jpg",         alt: "Silk organza ruffle blouse" },
  pieceBluePurple:    { src: "images/garment-blue-purple-twopiece.jpg", alt: "Blue and purple two-piece" },
};

// Photo component — three ways to pass an image:
//   <Photo name="susanKente" />            // pinned, by name
//   <Photo photo={feedPhoto} />            // feed item ({src, caption, ...})
//   <Photo src="..." label="..." />        // raw
function Photo({ name, photo, src, alt, label, h, aspectRatio, tone, style, pos, className = "", ...rest }) {
  let resolved = null;
  let resolvedLabel = label;
  let resolvedPos = pos;

  if (name && PINNED_PHOTOS[name]) {
    resolved = PINNED_PHOTOS[name];
    resolvedLabel = label || resolved.alt;
    resolvedPos = pos || resolved.pos;
  } else if (photo) {
    resolved = { src: photo.src, alt: photo.caption || photo.alt };
    resolvedLabel = label || photo.caption || photo.alt || "—";
  } else if (src) {
    resolved = { src, alt: alt || label };
    resolvedLabel = label || alt;
  }

  const cls = `ph ${tone || ""} ${resolved ? "has-photo" : ""} ${className}`.trim();
  const wrapperStyle = {
    ...(h ? { height: h } : {}),
    ...(aspectRatio ? { aspectRatio } : {}),
    ...style,
  };
  return (
    <div className={cls} data-pos={resolvedPos || undefined} role="img" aria-label={resolved?.alt || resolvedLabel} {...rest} style={wrapperStyle}>
      {resolved && <div className="ph-bg" style={{ backgroundImage: `url("${resolved.src}")` }} />}
      <span className="ph-label">{resolvedLabel || "—"}</span>
    </div>
  );
}

function Wordmark({ size = 22, color = "var(--ink)", href = "index.html" }) {
  return (
    <a href={href} style={{ display: "flex", alignItems: "baseline", gap: 8, textDecoration: "none", color }}>
      <span className="display" style={{ fontSize: size, fontStyle: "italic", letterSpacing: "-0.02em" }}>Susan's</span>
      <span style={{ fontFamily: "var(--sans)", fontSize: size * 0.5, letterSpacing: "0.24em", textTransform: "uppercase", fontWeight: 500 }}>Couture</span>
    </a>
  );
}

function Nav({ tone = "light", floating = false }) {
  const dark = tone === "dark";
  return (
    <nav style={{
      position: floating ? "absolute" : "relative",
      top: 0, left: 0, right: 0, zIndex: 5,
      padding: "22px 48px",
      display: "flex",
      alignItems: "center",
      justifyContent: "space-between",
      color: dark ? "var(--bone)" : "var(--ink)",
      borderBottom: floating ? "none" : "1px solid var(--hairline)",
    }}>
      <Wordmark color={dark ? "var(--bone)" : "var(--ink)"} />
      <div style={{ display: "flex", gap: 36 }}>
        {NAV_ITEMS.map(n => (
          <a key={n.label} href={n.href} style={{
            color: "inherit",
            textDecoration: "none",
            fontSize: 12,
            letterSpacing: "0.16em",
            textTransform: "uppercase",
            fontWeight: 500,
            opacity: 0.9
          }}>{n.label}</a>
        ))}
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 18, fontSize: 12, letterSpacing: "0.12em", textTransform: "uppercase" }}>
        <a href="tel:+447762227836" style={{ color: "inherit", textDecoration: "none", display: "flex", alignItems: "center", gap: 8 }}>
          <span style={{ width: 6, height: 6, borderRadius: "50%", background: "var(--terracotta)", display: "inline-block" }} />
          07762 227 836
        </a>
      </div>
    </nav>
  );
}

function Footer() {
  return (
    <footer style={{
      background: "var(--ink)",
      color: "var(--bone)",
      padding: "80px 48px 36px",
      fontFamily: "var(--sans)",
    }}>
      <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr 1fr 1fr", gap: 64, paddingBottom: 64, borderBottom: "1px solid rgba(245,239,230,.15)" }}>
        <div>
          <div className="display" style={{ fontFamily: "var(--serif)", fontSize: 36, fontStyle: "italic", marginBottom: 16 }}>Susan's Couture</div>
          <p className="body" style={{ color: "rgba(245,239,230,.7)", maxWidth: 320, fontSize: 14 }}>
            Bespoke Ghanaian and European garments, hand-tailored in London since 1998.
          </p>
        </div>
        <FooterCol title="Visit" items={[{label:"The Studio", href:"Visit.html"}, {label:"By appointment", href:"Visit.html"}, {label:"Mon–Sat, 11–18", href:"Visit.html"}]} />
        <FooterCol title="Explore" items={[{label:"Home", href:"index.html"}, ...NAV_ITEMS.map(n => ({label:n.label, href:n.href}))]} />
        <FooterCol title="Follow" items={[{label:"Instagram @susans_couture", href:"https://instagram.com/susans_couture"}, {label:"Call studio", href:"tel:+447762227836"}]} />
      </div>
      <div style={{ display: "flex", justifyContent: "space-between", paddingTop: 28, fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase", color: "rgba(245,239,230,.5)" }}>
        <span>© 2026 Susan's Couture · London</span>
        <span>Made with care</span>
      </div>
    </footer>
  );
}
function FooterCol({ title, items }) {
  return (
    <div>
      <div className="eyebrow" style={{ color: "rgba(245,239,230,.5)", marginBottom: 18 }}>{title}</div>
      <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 10 }}>
        {items.map(i => (
          <li key={i.label} style={{ fontSize: 14 }}>
            <a href={i.href} style={{ color: "rgba(245,239,230,.85)", textDecoration: "none" }}>{i.label}</a>
          </li>
        ))}
      </ul>
    </div>
  );
}

function InstagramStrip() {
  const feed = usePhotos();
  // Take the latest 7 for the collage (one big anchor + six smaller).
  const items = feed.slice(0, 7);
  if (items.length === 0) return null;

  const [hero, ...rest] = items;
  // Pad to 6 small tiles by re-using the start of the feed if needed
  const small = rest.length >= 6 ? rest.slice(0, 6) : [...rest, ...feed.slice(0, 6 - rest.length)].slice(0, 6);

  return (
    <section style={{ padding: "120px 48px", background: "var(--paper)", position: "relative", overflow: "hidden" }}>
      <div style={{ maxWidth: 1400, margin: "0 auto", position: "relative" }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", marginBottom: 48, position: "relative" }}>
        <div>
          <div className="eyebrow">@susans_couture · Instagram</div>
          <h2 style={{ fontSize: 56, margin: "8px 0 0", lineHeight: 1 }}>From the studio<span style={{ fontStyle: "italic" }}>, this week.</span></h2>
          <p className="body" style={{ fontSize: 14, color: "var(--mute)", marginTop: 12, maxWidth: 460 }}>
            Susan posts what's on the table — fittings, finished pieces, fabric runs. The site updates as she does.
          </p>
        </div>
        <a className="sc-link" href="https://instagram.com/susans_couture">Follow on Instagram →</a>
      </div>

      {/* Asymmetric collage: 1 large hero photo + 6 mosaic tiles in a 12-col grid */}
      <div style={{
        display: "grid",
        gridTemplateColumns: "repeat(12, 1fr)",
        gridTemplateRows: "repeat(6, 90px)",
        gap: 12,
        position: "relative",
      }}>
        {/* Large anchor — top-left, 5 cols × 4 rows */}
        <IGTile photo={hero} style={{ gridColumn: "1 / span 5", gridRow: "1 / span 4" }} large />
        {/* Top-right cluster — varied sizes */}
        <IGTile photo={small[0]} style={{ gridColumn: "6 / span 4", gridRow: "1 / span 3" }} />
        <IGTile photo={small[1]} style={{ gridColumn: "10 / span 3", gridRow: "1 / span 2" }} />
        <IGTile photo={small[2]} style={{ gridColumn: "10 / span 3", gridRow: "3 / span 3" }} />
        {/* Bottom row */}
        <IGTile photo={small[3]} style={{ gridColumn: "1 / span 3", gridRow: "5 / span 2" }} />
        <IGTile photo={small[4]} style={{ gridColumn: "4 / span 3", gridRow: "5 / span 2" }} />
        <IGTile photo={small[5]} style={{ gridColumn: "7 / span 3", gridRow: "4 / span 3" }} />
      </div>

      {/* Caption ticker beneath */}
      <div style={{ marginTop: 32, display: "flex", justifyContent: "space-between", alignItems: "center", fontFamily: "var(--mono)", fontSize: 11, color: "var(--mute)", letterSpacing: "0.08em", textTransform: "uppercase" }}>
        <span>● Live feed · last updated {new Date(items[0].date).toLocaleDateString("en-GB", { day: "numeric", month: "long" })}</span>
        <span>{feed.length} posts in the archive →</span>
      </div>
      </div>
    </section>
  );
}

function IGTile({ photo, style, large }) {
  if (!photo) return null;
  return (
    <a href="#" style={{ ...style, position: "relative", overflow: "hidden", textDecoration: "none" }} className="ig-tile">
      <div style={{
        position: "absolute", inset: 0,
        backgroundImage: `url("${photo.src}")`,
        backgroundSize: "cover",
        backgroundPosition: "center",
        transition: "transform .8s ease",
      }} />
      <div style={{
        position: "absolute", inset: 0,
        background: "linear-gradient(180deg, transparent 50%, rgba(42,31,23,.55))",
        opacity: 0,
        transition: "opacity .25s",
      }} className="ig-tile-shade" />
      <div className="ig-tile-cap" style={{
        position: "absolute", left: 14, right: 14, bottom: 12,
        color: "var(--bone)",
        fontFamily: "var(--serif)",
        fontStyle: "italic",
        fontSize: large ? 18 : 13,
        lineHeight: 1.25,
        opacity: 0,
        transform: "translateY(6px)",
        transition: "opacity .25s, transform .25s",
      }}>{photo.caption}</div>
    </a>
  );
}

function VisitBlock({ tone = "light" }) {
  const dark = tone === "dark";
  return (
    <section style={{
      padding: "120px 48px",
      background: dark ? "var(--ink)" : "var(--bone)",
      color: dark ? "var(--bone)" : "var(--ink)",
    }}>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 80, alignItems: "center", maxWidth: 1280, margin: "0 auto" }}>
        <div>
          <div className="eyebrow" style={{ color: dark ? "rgba(245,239,230,.6)" : "var(--mute)" }}>Visit the studio</div>
          <h2 style={{ fontSize: 64, margin: "16px 0 24px", lineHeight: 1 }}>
            We don't do <span style={{ fontStyle: "italic" }}>online forms.</span>
          </h2>
          <p className="body" style={{ fontSize: 18, color: dark ? "rgba(245,239,230,.75)" : "var(--ink-soft)", maxWidth: 480, marginBottom: 32 }}>
            Every garment begins with a conversation. Pick up the phone, or come into the studio for fabric, opinions, and a proper look at the cloth.
          </p>
          <div style={{ display: "flex", gap: 12, flexWrap: "wrap" }}>
            <a className="sc-btn" href="tel:+447762227836" style={dark ? { background: "var(--bone)", color: "var(--ink)", borderColor: "var(--bone)" } : {}}>Call the studio</a>
            <a className="sc-btn ghost" href="Visit.html" style={dark ? { color: "var(--bone)", borderColor: "rgba(245,239,230,.4)" } : {}}>Visit the studio</a>
          </div>
          <div style={{ marginTop: 48, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 32 }}>
            <Detail label="Address" lines={["C1 & C2, Tooting Broadway Market", "Tooting, London", "SW17 0SN"]} dark={dark} />
            <Detail label="Hours" lines={["Mon – Fri  11 – 18", "Saturday  11 – 16", "Sun  by appointment"]} dark={dark} />
          </div>
        </div>
        <Photo name="shopFive" label="Studio interior · gowns lined up" aspectRatio="4/5" />
      </div>
    </section>
  );
}
function Detail({ label, lines, dark }) {
  return (
    <div>
      <div className="eyebrow" style={{ color: dark ? "rgba(245,239,230,.5)" : "var(--mute)", marginBottom: 10 }}>{label}</div>
      {lines.map((l, i) => (
        <div key={i} style={{ fontSize: 14, color: dark ? "rgba(245,239,230,.85)" : "var(--ink-soft)", lineHeight: 1.7 }}>{l}</div>
      ))}
    </div>
  );
}

function MarqueeBand({ items, accent = "var(--terracotta)" }) {
  const repeated = [...items, ...items, ...items];
  return (
    <div style={{
      borderTop: "1px solid var(--hairline)",
      borderBottom: "1px solid var(--hairline)",
      overflow: "hidden",
      background: "var(--paper)",
      padding: "22px 0",
    }}>
      <div style={{
        display: "flex",
        gap: 48,
        whiteSpace: "nowrap",
        animation: "sc-marquee 40s linear infinite",
        fontFamily: "var(--serif)",
        fontStyle: "italic",
        fontSize: 28,
        color: "var(--ink)",
      }}>
        {repeated.map((it, i) => (
          <span key={i} style={{ display: "inline-flex", alignItems: "center", gap: 48 }}>
            {it}
            <span style={{ width: 6, height: 6, borderRadius: "50%", background: accent, display: "inline-block" }} />
          </span>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { Nav, Footer, InstagramStrip, VisitBlock, Wordmark, MarqueeBand, Photo, PINNED_PHOTOS });
