// Karavi Studio · Product Detail Page (motion-refreshed)
const Product = ({ id, goto, addToCart }) => {
  const { useState } = React;
  const products = window.KARAVI_PRODUCTS;
  const p = products.find(x => x.id === id) || products[0];
  const [size, setSize] = useState(p.sizes[0]);
  const [swatch, setSwatch] = useState(0);
  const [tab, setTab] = useState("Material");
  const [added, setAdded] = useState(false);

  const swatchNames = ["Olive", "Clay", "Stone", "Rose", "Cosmos", "Sage", "Cream", "Bone"];
  const others = products.filter(x => x.id !== p.id && x.category === p.category).slice(0, 4);

  const handleAddToCart = () => {
    addToCart(p, size);
    setAdded(true);
    setTimeout(() => setAdded(false), 1800);
  };

  return (
    <main>
      {/* ── BREADCRUMB ───────────────────────── */}
      <Section style={{ paddingTop: 20, paddingBottom: 8 }}>
        <motion.div
          initial={{ opacity: 0, y: 6 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.4, delay: 0.1 }}
          style={{ fontSize: 11, letterSpacing: ".18em", textTransform: "uppercase", color: "var(--fg-3)", display: "flex", gap: 8, flexWrap: "wrap" }}
        >
          <a onClick={() => goto("home")} style={{ border: 0, cursor: "pointer", color: "inherit" }}>Home</a>
          <span>·</span>
          <a onClick={() => goto(`category:${p.category}`)} style={{ border: 0, cursor: "pointer", color: "inherit" }}>{p.category}</a>
          <span>·</span>
          <span style={{ color: "var(--fg-1)" }}>{p.name}</span>
        </motion.div>
      </Section>

      {/* ── MAIN LAYOUT ──────────────────────── */}
      <Section className="k-2col-layout" style={{
        display: "grid", gridTemplateColumns: "1.35fr 1fr", gap: 56, marginTop: 18,
        alignItems: "start",
      }}>
        {/* Gallery */}
        <Stagger style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }} delayChildren={0.05} staggerChildren={0.12}>
          <StaggerItem style={{ gridColumn: "1 / 3" }}>
            <motion.div
              whileHover={{ scale: 1.005 }}
              transition={{ duration: 0.4 }}
              className="k-card-img-wrap"
              style={{
                aspectRatio: "4/3", borderRadius: 22,
                background: "var(--karavi-bone)",
                boxShadow: "var(--shadow-sm)",
              }}>
              <div className="k-card-img" style={{ backgroundImage: `url(${p.image})` }}/>
            </motion.div>
          </StaggerItem>
          <StaggerItem>
            <motion.div whileHover={{ scale: 1.01 }} transition={{ duration: 0.4 }} className="k-card-img-wrap" style={{
              aspectRatio: "1/1", borderRadius: 22,
              background: "var(--karavi-bone)",
            }}>
              <div className="k-card-img" style={{ backgroundImage: "url(project/assets/textures-grid.jpg)" }}/>
            </motion.div>
          </StaggerItem>
          <StaggerItem>
            <motion.div whileHover={{ scale: 1.01 }} transition={{ duration: 0.4 }} className="k-card-img-wrap" style={{
              aspectRatio: "1/1", borderRadius: 22,
              background: "var(--karavi-bone)",
            }}>
              <div className="k-card-img" style={{ backgroundImage: "url(project/assets/rug-organic-shapes.jpg)" }}/>
            </motion.div>
          </StaggerItem>
        </Stagger>

        {/* Meta panel */}
        <motion.div
          initial={{ opacity: 0, x: 30 }}
          animate={{ opacity: 1, x: 0 }}
          transition={{ duration: 0.6, ease: [0.22, 0.61, 0.36, 1], delay: 0.1 }}
          style={{
            position: "sticky", top: 88,
            alignSelf: "flex-start", display: "flex", flexDirection: "column", gap: 22,
          }}
        >
          <div>
            <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
              <Eyebrow>{p.type}</Eyebrow>
              {p.new && <Badge>New In</Badge>}
              {p.was && <Badge tone="cosmos">{`−${Math.round((1 - p.price / p.was) * 100)}%`}</Badge>}
            </div>
            <h1 style={{
              fontFamily: "var(--font-display)", fontWeight: 400,
              fontSize: "clamp(36px, 4vw, 52px)", lineHeight: 1.05,
              letterSpacing: "-0.01em", marginTop: 10,
            }}>
              {p.name}<br/><em style={{ fontWeight: 300 }}>{p.sub}</em>
            </h1>
          </div>

          <p style={{ fontSize: 16, lineHeight: 1.65, color: "var(--fg-1)", maxWidth: 440, margin: 0 }}>{p.blurb}</p>

          <div style={{ display: "flex", gap: 14, alignItems: "baseline" }}>
            <span style={{ fontFamily: "var(--font-display)", fontSize: 26, color: "var(--fg-display)" }}>
              ₹ {p.price.toLocaleString("en-IN")}
            </span>
            {p.was && (
              <s style={{ color: "var(--fg-3)", fontSize: 16 }}>₹ {p.was.toLocaleString("en-IN")}</s>
            )}
          </div>

          {/* Swatches */}
          <div>
            <Eyebrow style={{ marginBottom: 10 }}>
              Colour · {swatchNames[swatch] || "Select"}
            </Eyebrow>
            <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
              {p.swatches.map((s, i) => (
                <motion.button
                  key={i}
                  onClick={() => setSwatch(i)}
                  whileHover={{ scale: 1.1 }}
                  whileTap={{ scale: 0.92 }}
                  animate={{ scale: swatch === i ? 1.05 : 1 }}
                  transition={springs.pop}
                  aria-label={`Select colour ${swatchNames[i] || i + 1}`}
                  style={{
                    width: 36, height: 36, borderRadius: 999, border: 0,
                    cursor: "pointer", background: s, padding: 0,
                    outline: swatch === i ? "2px solid var(--karavi-ebony)" : "1px solid var(--line-medium)",
                    outlineOffset: swatch === i ? 3 : 0,
                    boxShadow: "var(--shadow-inset)",
                  }}
                />
              ))}
            </div>
          </div>

          {/* Size selector */}
          <div>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 10 }}>
              <Eyebrow>Size</Eyebrow>
              <button style={{
                background: "none", border: 0, cursor: "pointer",
                fontSize: 12, color: "var(--fg-2)", borderBottom: "1px solid var(--fg-2)",
                padding: "2px 0", minHeight: 36,
              }}>Sizing guide</button>
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              {p.sizes.map(s => (
                <motion.button
                  key={s}
                  onClick={() => setSize(s)}
                  whileHover={{ x: 2 }}
                  whileTap={{ scale: 0.99 }}
                  animate={{
                    background: size === s ? "var(--karavi-bone)" : "rgba(0,0,0,0)",
                  }}
                  transition={{ duration: 0.2 }}
                  style={{
                    fontFamily: "var(--font-body)", fontSize: 14, padding: "14px 18px",
                    border: `1px solid ${size === s ? "var(--karavi-ebony)" : "var(--line-medium)"}`,
                    borderRadius: 14, textAlign: "left", cursor: "pointer",
                    color: "var(--fg-1)", minHeight: 52,
                  }}
                >{s}</motion.button>
              ))}
            </div>
          </div>

          {/* CTA */}
          <div style={{ display: "flex", gap: 10 }}>
            <Button
              full
              magnetic
              onClick={handleAddToCart}
              style={added ? { background: "var(--status-success)" } : {}}
            >
              <AnimatePresence mode="wait">
                <motion.span
                  key={added ? "added" : "add"}
                  initial={{ opacity: 0, y: 8 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: -8 }}
                  transition={{ duration: 0.2 }}
                >
                  {added ? "Added to bag ✓" : "Add to bag"}
                </motion.span>
              </AnimatePresence>
            </Button>
            <Button
              variant="secondary"
              aria-label="Add to wishlist"
              style={{ flex: "0 0 auto", padding: "14px 18px" }}
            >
              <Icon name="heart" size={16}/>
            </Button>
          </div>

          <div style={{ display: "flex", gap: 10, alignItems: "center", fontSize: 13, color: "var(--fg-2)" }}>
            <Icon name="truck" size={16}/>
            <span>Made to order · ships in 5–7 days · free above ₹ 4,000</span>
          </div>

          {/* Tabs */}
          <div style={{ marginTop: 8, borderTop: "1px solid var(--line-soft)", paddingTop: 20 }}>
            <div style={{ display: "flex", gap: 24, marginBottom: 16, position: "relative" }}>
              {["Material", "Care", "The Maker"].map(t => (
                <motion.button
                  key={t}
                  onClick={() => setTab(t)}
                  whileHover={{ y: -1 }}
                  style={{
                    background: "none", border: 0, cursor: "pointer", padding: "0 0 8px",
                    fontSize: 12, letterSpacing: ".22em", textTransform: "uppercase",
                    color: tab === t ? "var(--fg-display)" : "var(--fg-3)",
                    minHeight: 36, position: "relative",
                  }}
                >
                  {t}
                  {tab === t && (
                    <motion.div
                      layoutId="tab-underline"
                      transition={springs.gentle}
                      style={{
                        position: "absolute", bottom: 0, left: 0, right: 0,
                        height: 1.5, background: "var(--fg-display)",
                      }}
                    />
                  )}
                </motion.button>
              ))}
            </div>
            <AnimatePresence mode="wait">
              <motion.p
                key={tab}
                initial={{ opacity: 0, y: 6 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -6 }}
                transition={{ duration: 0.22 }}
                style={{ fontSize: 14, lineHeight: 1.7, color: "var(--fg-2)", maxWidth: 440, margin: 0 }}
              >
                {tab === "Material" && (p.detail?.material || "Natural fibres, made by hand.")}
                {tab === "Care" && (p.detail?.care || "Please handle with care. Refer to care label.")}
                {tab === "The Maker" && (p.detail?.maker || "Made by skilled artisans in India.")}
              </motion.p>
            </AnimatePresence>
          </div>
        </motion.div>
      </Section>

      {/* ── PULL QUOTE ───────────────────────── */}
      <Section style={{ marginTop: 112, textAlign: "center" }}>
        <KilimDivider/>
        <Reveal delay={0.15}>
          <div style={{
            fontFamily: "var(--font-display)", fontStyle: "italic", fontSize: "clamp(22px, 3vw, 40px)",
            lineHeight: 1.25, color: "var(--fg-display)",
            maxWidth: 820, margin: "48px auto 0",
          }}>
            "Made in a workshop of three, in a town where every house still hears a loom."
          </div>
        </Reveal>
      </Section>

      {/* ── RELATED ──────────────────────────── */}
      {others.length > 0 && (
        <Section style={{ marginTop: 96 }}>
          <Reveal>
            <Eyebrow>Pieces nearby</Eyebrow>
            <h2 style={{
              fontFamily: "var(--font-display)", fontWeight: 300,
              fontSize: "clamp(28px, 3.4vw, 44px)", marginTop: 8, marginBottom: 32,
            }}>
              From the same hands.
            </h2>
          </Reveal>
          <Stagger className="k-grid-4">
            {others.map(o => (
              <StaggerItem key={o.id}>
                <ProductCard p={o} onClick={() => goto(`product:${o.id}`)}/>
              </StaggerItem>
            ))}
          </Stagger>
        </Section>
      )}
    </main>
  );
};
window.Product = Product;
