// ---------- ACCORDION ----------
const Accordion = ({ title, defaultOpen = false, children }) => {
  const [open, setOpen] = React.useState(defaultOpen);
  return (
    <div style={{ borderBottom: "1px solid var(--rule)" }}>
      <button
        onClick={() => setOpen(!open)}
        style={{
          width: "100%",
          display: "flex", alignItems: "center", justifyContent: "space-between",
          padding: "20px 0",
          textAlign: "left",
        }}
      >
        <span className="serif" style={{ fontSize: 18, color: "var(--ink)", fontWeight: 500 }}>{title}</span>
        <span style={{ color: "var(--muted)", transform: open ? "rotate(45deg)" : "rotate(0)", transition: "transform .25s ease" }}>
          <IconPlus size={16} />
        </span>
      </button>
      <div style={{
        maxHeight: open ? 600 : 0,
        overflow: "hidden",
        transition: "max-height .35s ease",
      }}>
        <div style={{ padding: "0 0 24px", fontSize: 14, color: "var(--text)", lineHeight: 1.65 }}>
          {children}
        </div>
      </div>
    </div>
  );
};

// ---------- GALLERY ----------
const Gallery = ({ watch }) => {
  const [idx, setIdx] = React.useState(0);
  const realImages = Array.isArray(watch.images) ? watch.images.slice(0, 8) : [];
  const hasRealImages = realImages.length > 0;
  const views = hasRealImages
    ? realImages.map((_, i) => `View ${i + 1}`)
    : ["Front", "Three-quarter", "Dial macro", "Case back", "On wrist"];

  React.useEffect(() => { setIdx(0); }, [watch.id]);

  const renderMain = () => {
    if (hasRealImages) {
      return (
        <div style={{
          position: "relative",
          width: "100%",
          aspectRatio: "4 / 5",
          background: "#FFFFFF",
          overflow: "hidden", borderRadius: 2,
        }}>
          <img
            src={realImages[idx]}
            alt={`${watch.brand} ${watch.model} — view ${idx + 1}`}
            style={{
              position: "absolute", inset: 0,
              width: "100%", height: "100%",
              objectFit: "contain", padding: "5%",
            }}
          />
        </div>
      );
    }
    return <WatchPlate watch={watch} large />;
  };

  return (
    <div>
      <div style={{ position: "relative" }}>
        {renderMain()}
        <div style={{
          position: "absolute", top: 16, left: 16,
          background: hexA("#FFFFFF", 0.9),
          color: "var(--ink)",
          fontSize: 10,
          letterSpacing: "0.16em",
          textTransform: "uppercase",
          padding: "7px 11px",
          fontFamily: "var(--mono)"
        }}>
          {views[idx]}
        </div>
        <div style={{
          position: "absolute", top: 16, right: 16,
          display: "flex", gap: 6,
        }}>
          <button
            onClick={() => setIdx((idx - 1 + views.length) % views.length)}
            aria-label="Previous"
            style={{
              width: 38, height: 38, background: hexA("#FFFFFF", 0.9),
              display: "grid", placeItems: "center", color: "var(--ink)"
            }}>
            <IconChevronLeft size={16} />
          </button>
          <button
            onClick={() => setIdx((idx + 1) % views.length)}
            aria-label="Next"
            style={{
              width: 38, height: 38, background: hexA("#FFFFFF", 0.9),
              display: "grid", placeItems: "center", color: "var(--ink)"
            }}>
            <IconChevronRight size={16} />
          </button>
        </div>
      </div>

      <div style={{
        display: "grid",
        gridTemplateColumns: `repeat(${views.length}, 1fr)`,
        gap: 10,
        marginTop: 12,
      }}>
        {views.map((v, i) => (
          <button key={i} onClick={() => setIdx(i)}
            style={{
              aspectRatio: "1",
              outline: i === idx ? "1px solid var(--gold-deep)" : "1px solid var(--rule)",
              outlineOffset: -1,
              padding: 0,
              position: "relative",
              overflow: "hidden",
              background: "#FFFFFF",
            }}>
            {hasRealImages ? (
              <img
                src={realImages[i]}
                alt=""
                style={{
                  width: "100%", height: "100%",
                  objectFit: "contain", padding: "8%",
                  opacity: i === idx ? 1 : 0.7,
                }}
              />
            ) : (
              <div style={{ transform: "scale(0.95)", transformOrigin: "center", opacity: i === idx ? 1 : 0.7 }}>
                <WatchPlate watch={watch} label={false} />
              </div>
            )}
          </button>
        ))}
      </div>
    </div>
  );
};

// ---------- BREADCRUMB ----------
const Crumbs = ({ watch, onHome, onShop }) => (
  <div style={{
    maxWidth: 1440, margin: "0 auto",
    padding: "20px clamp(18px, 4vw, 44px) 0",
    fontSize: 12, letterSpacing: "0.1em",
    textTransform: "uppercase", color: "var(--muted)",
  }}>
    <button onClick={onHome}>Home</button>
    <span style={{ margin: "0 10px", opacity: 0.5 }}>/</span>
    <button onClick={onShop || onHome}>Collection</button>
    <span style={{ margin: "0 10px", opacity: 0.5 }}>/</span>
    <span style={{ color: "var(--ink)" }}>{watch.brand} · {watch.model.split(" — ")[0]}</span>
  </div>
);

// Misma marca y categoría primero; se completa con el resto de la categoría.
// Evita que un Cartier muestre cuatro Rolex como "similares".
const relatedFor = (watch) => {
  const rest = WATCHES.filter(w => w.id !== watch.id && w.category === watch.category);
  const sameBrand = rest.filter(w => w.brand === watch.brand);
  return [...sameBrand, ...rest.filter(w => w.brand !== watch.brand)].slice(0, 4);
};

// ---------- PRODUCT PAGE ----------
const ProductPage = ({ watchId, onHome, onShop, onInquire, catalogReady }) => {
  const watch = WATCHES.find(w => w.id === watchId);
  const [offerHover, setOfferHover] = React.useState(false);

  React.useEffect(() => { window.scrollTo(0, 0); }, [watchId]);

  // Deep link: el catálogo puede seguir cargando, o el id ya no existir.
  if (!watch) {
    return (
      <main style={{ padding: "clamp(80px, 14vw, 160px) 24px", textAlign: "center" }}>
        {catalogReady ? (
          <>
            <div className="eyebrow" style={{ color: "var(--gold-deep)" }}>Not found</div>
            <h1 className="serif" style={{ fontSize: "clamp(28px, 4vw, 44px)", color: "var(--ink)", margin: "12px 0 10px", fontWeight: 500 }}>
              This piece is no longer listed.
            </h1>
            <p style={{ color: "var(--muted)", fontSize: 15, margin: "0 auto 26px", maxWidth: 440 }}>
              It may have been sold or delisted. Browse the current collection — or ask us to source one for you.
            </p>
            <PrimaryButton onClick={() => (onShop ? onShop() : onHome())}>View the collection</PrimaryButton>
          </>
        ) : (
          <div style={{ color: "var(--muted)", fontSize: 14, letterSpacing: "0.08em" }}>Loading…</div>
        )}
      </main>
    );
  }

  return (
    <main>
      <Crumbs watch={watch} onHome={onHome} onShop={onShop} />

      <div style={{
        maxWidth: 1440, margin: "0 auto",
        padding: "24px clamp(18px, 4vw, 44px) clamp(40px, 6vw, 80px)",
        display: "grid",
        gridTemplateColumns: "minmax(0, 1.1fr) minmax(0, 1fr)",
        gap: "clamp(24px, 4vw, 72px)",
        alignItems: "start",
      }} className="pdp-grid">
        {/* LEFT */}
        <div style={{ position: "sticky", top: 80 }} className="pdp-left">
          <Gallery watch={watch} />
        </div>

        {/* RIGHT */}
        <div>
          {/* Certified dealer badge */}
          <div style={{
            display: "inline-flex", alignItems: "center", gap: 8,
            border: "1px solid var(--gold)",
            padding: "8px 14px",
            color: "var(--gold-deep)",
            fontSize: 11, letterSpacing: "0.16em",
            textTransform: "uppercase", fontFamily: "var(--mono)",
            marginBottom: 22,
          }}>
            <IconShield size={14} /> Brytez — Independent Dealer
          </div>

          <div style={{ fontSize: 12, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)" }}>
            {watch.brand}
          </div>
          <h1 className="serif" style={{
            fontSize: "clamp(30px, 3.6vw, 46px)",
            lineHeight: 1.1,
            margin: "8px 0 6px",
            color: "var(--ink)",
            fontWeight: 500,
            textWrap: "balance",
          }}>
            {watch.model}
          </h1>
          <div style={{ fontSize: 12, color: "var(--muted)", marginBottom: 22, fontFamily: "var(--mono)", letterSpacing: "0.06em" }}>
            {[
              watch.reference && `Ref. ${watch.reference}`,
              watch.condition,
              watch.box && "Box",
              watch.papers && "Papers",
            ].filter(Boolean).join(" · ")}
          </div>

          {/* Price */}
          <div style={{
            display: "flex", alignItems: "baseline", gap: 14, flexWrap: "wrap",
            paddingBottom: 20, borderBottom: "1px solid var(--rule)",
          }}>
            <div className="serif" style={{ fontSize: 44, color: "var(--ink)", lineHeight: 1, fontWeight: 500 }}>
              {watch.price_display || "Price on request"}
            </div>
          </div>

          {/* Authenticity strip */}
          <div style={{
            display: "flex", alignItems: "center", gap: 12,
            background: hexA("#212A3D", 0.05),
            border: `1px solid ${hexA("#212A3D", 0.15)}`,
            padding: "14px 16px",
            marginTop: 20,
          }}>
            <div style={{ color: "var(--green)" }}><IconShield size={22} /></div>
            <div>
              <div style={{ fontSize: 13, color: "var(--ink)", fontWeight: 500 }}>
                Verified Authentic
              </div>
              <div style={{ fontSize: 12, color: "var(--muted)", marginTop: 2 }}>
                Serial and documentation checked on every sale
              </div>
            </div>
          </div>

          {/* CTAs */}
          <div style={{ display: "grid", gap: 10, marginTop: 22 }}>
            <PrimaryButton
              full
              icon={<IconWhatsApp size={18} color="#fff" />}
              onClick={() => onInquire(watch)}
            >
              Inquire via WhatsApp
            </PrimaryButton>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }} className="pdp-secondary">
              <button
                onClick={() => onInquire(watch)}
                onMouseEnter={() => setOfferHover(true)}
                onMouseLeave={() => setOfferHover(false)}
                style={{
                  padding: "13px 20px",
                  border: `1px solid ${offerHover ? "var(--gold-deep)" : "var(--gold)"}`,
                  background: offerHover ? hexA("#A86137", 0.08) : "transparent",
                  color: "var(--gold-deep)",
                  fontSize: 12,
                  letterSpacing: "0.16em",
                  textTransform: "uppercase",
                  transition: "all .2s ease",
                }}>
                Make an Offer
              </button>
              <GhostButton onClick={() => onInquire(watch)}>Contact Expert</GhostButton>
            </div>
          </div>

          {/* Quick facts row */}
          <div style={{
            display: "grid",
            gridTemplateColumns: "repeat(3, 1fr)",
            gap: 0,
            marginTop: 30,
            border: "1px solid var(--rule)",
          }}>
            {[
              ["Ref.", watch.reference || "On request"],
              ["Verified", "Before delivery"],
              ["Inquiries", "WhatsApp"],
            ].map(([k, v], i) => (
              <div key={k} style={{
                padding: "14px 16px",
                borderRight: i < 2 ? "1px solid var(--rule)" : "none",
              }}>
                <div style={{ fontSize: 10, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--muted)" }}>{k}</div>
                <div style={{ fontSize: 13, color: "var(--ink)", marginTop: 4 }}>{v}</div>
              </div>
            ))}
          </div>

          {/* Summary */}
          <p style={{ fontSize: 15, lineHeight: 1.7, color: "var(--text)", marginTop: 28, textWrap: "pretty" }}>
            {watch.summary}
          </p>

          {/* Accordions */}
          <div style={{ marginTop: 24 }}>
            <Accordion title="Watch details" defaultOpen>
              <dl style={{ margin: 0, display: "grid", gridTemplateColumns: "140px 1fr", rowGap: 10, columnGap: 20 }}>
                {Object.entries(watch.specs).map(([k, v]) => (
                  <React.Fragment key={k}>
                    <dt style={{ fontSize: 12, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--muted)" }}>
                      {k === "water" ? "Water res." : k === "case" ? "Case" : k.charAt(0).toUpperCase() + k.slice(1)}
                    </dt>
                    <dd style={{ margin: 0, color: "var(--ink)", fontSize: 14 }}>{v}</dd>
                  </React.Fragment>
                ))}
              </dl>
            </Accordion>

            <Accordion title="Condition & photos">
              <p style={{ margin: 0 }}>
                Condition is confirmed piece by piece before we quote. Ask on WhatsApp for additional
                high-resolution photos or a live video of this exact watch — we'll walk you through it.
              </p>
            </Accordion>

            <Accordion title="Authenticity & provenance">
              <p style={{ margin: 0 }}>
                Every timepiece is verified before delivery: serial and reference numbers are checked against the supplying dealer's records, and the watch's documentation is reviewed piece by piece. Additional photos or a live video call are available on request before you commit.
              </p>
            </Accordion>
          </div>

          {/* Specialist card */}
          <div style={{
            marginTop: 32,
            padding: 20,
            background: "var(--paper)",
            display: "flex", gap: 14, alignItems: "center",
          }}>
            <div style={{
              width: 52, height: 52, borderRadius: "50%",
              background: "#1F2630", color: "#F4F2EF",
              display: "grid", placeItems: "center",
              fontFamily: "var(--serif)", fontSize: 20,
            }}>G</div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--muted)" }}>Your contact</div>
              <div style={{ fontSize: 15, color: "var(--ink)", fontWeight: 500 }}>Gabriel · Miami</div>
              <div style={{ fontSize: 12, color: "var(--muted)", marginTop: 2 }}>Your direct line on WhatsApp — replies personally</div>
            </div>
          </div>
        </div>

        <style>{`
          @media (max-width: 900px) {
            .pdp-grid { grid-template-columns: 1fr !important; }
            .pdp-left { position: static !important; }
          }
          @media (max-width: 480px) {
            .pdp-secondary { grid-template-columns: 1fr !important; }
          }
        `}</style>
      </div>

      {/* Related */}
      <section style={{ background: "var(--paper)", padding: "clamp(50px, 6vw, 80px) clamp(18px, 4vw, 44px)" }}>
        <div style={{ maxWidth: 1440, margin: "0 auto" }}>
          <div className="eyebrow" style={{ color: "var(--gold-deep)" }}>You may also consider</div>
          <span className="gold-rule" />
          <h3 className="serif" style={{ fontSize: "clamp(24px, 2.6vw, 32px)", margin: "6px 0 32px", color: "var(--ink)", fontWeight: 500 }}>
            Similar timepieces.
          </h3>
          <div style={{
            display: "grid",
            gridTemplateColumns: "repeat(auto-fit, minmax(220px, 1fr))",
            gap: "clamp(16px, 2vw, 28px)",
          }}>
            {relatedFor(watch).map((w) => (
              <WatchCard
                key={w.id}
                watch={w}
                onOpen={() => { onHome(w.id); }}
                onInquire={() => onInquire(w)}
              />
            ))}
          </div>
        </div>
      </section>
    </main>
  );
};

Object.assign(window, { ProductPage, Accordion });
