/* global React, KeraiMark, ScreenFrame, Display, Eyebrow, Body, PrimaryButton, themeTokens, useTheme, useReducedMotion, PALETTE, KeraiCommerce, TYPE, SERIF */
const { useState, useEffect, useRef } = React;
const KA = KeraiCommerce;
const EASE_A = "cubic-bezier(.22,.7,.2,1)";

const NOUN_A = { bracelets: "bracelet", earrings: "earrings", pendants: "pendant" };
const titledName = (product) => {
  const noun = NOUN_A[(product.label || product.box).toLowerCase()] || "";
  return new RegExp(noun, "i").test(product.name) ? product.name : `${product.name} ${noun}`;
};

/* A few layers that take turns: the current one sharpens in, the last
   one blurs away. Used by the attract pieces and the home reviews. */
function useTurns(count, interval, reduced) {
  const [idx, setIdx] = useState(0);
  useEffect(() => {
    if (reduced || count < 2) return;
    const id = setInterval(() => setIdx((i) => (i + 1) % count), interval);
    return () => clearInterval(id);
  }, [count, interval, reduced]);
  return idx;
}
const turnStyle = (active, reduced) => ({
  position: "absolute",
  inset: 0,
  opacity: active ? 1 : 0,
  filter: active ? "blur(0px)" : "blur(14px)",
  transform: active ? "scale(1)" : "scale(0.985)",
  transition: reduced ? "none" : `opacity 1.1s ease, filter 1.1s ease, transform 1.4s ${EASE_A}`,
  pointerEvents: "none",
});

/* ------------------------------------------------------------------ */
/* 01. ATTRACT                                                         */
/* Pieces take turns, each with the lowest price it can be bought at.  */
/* The film of the host inviting guests over replaces this when Kerai  */
/* supplies it.                                                        */
/* ------------------------------------------------------------------ */
const ATTRACT_IDS = ["ea-rndh", "pe-eme", "ea-ovlh", "pe-rndh", "ea-prn"];

function ScreenAttract({ theme, stock, onTap }) {
  const t = themeTokens(theme);
  const reduced = useReducedMotion();
  const pieces = ATTRACT_IDS.map((id) => KA.PRODUCT_BY_ID[id])
    .map((p) => {
      const prices = KA.MACHINE.metals.map((m) => KA.fromPrice(p, m, stock)).filter((x) => x != null);
      return prices.length ? { product: p, from: Math.min(...prices) } : null;
    })
    .filter(Boolean);
  const idx = useTurns(pieces.length, 5200, reduced);

  return (
    <ScreenFrame theme={theme}>
      <div onClick={onTap} style={{ position: "absolute", inset: 0, cursor: "pointer" }}>
        <div style={{ position: "absolute", top: 0, height: 230, left: 0, right: 0, display: "flex", alignItems: "center", justifyContent: "center" }}>
          <KeraiMark size={80} color={t.fg} />
        </div>

        <div style={{ position: "absolute", top: 290, left: (1080 - 720) / 2, width: 720, height: 720 }}>
          {pieces.map(({ product }, i) => (
            <div key={product.id} style={turnStyle(i === idx, reduced)}>
              <img src={KA.packshot(product, "white", null).src} alt="" draggable={false}
                   style={{ width: "100%", height: "100%", objectFit: "contain", display: "block" }} />
            </div>
          ))}
        </div>

        <div style={{ position: "absolute", top: 1040, left: 0, right: 0, height: 44 }}>
          {pieces.map(({ product, from }, i) => (
            <div key={product.id} style={{ ...turnStyle(i === idx, reduced), display: "flex", justifyContent: "center" }}>
              <Body size={30} style={{ color: t.fgMuted, whiteSpace: "nowrap" }}>
                {titledName(product)} <span style={{ color: t.fg }}>from {KA.formatMoney(from)}</span>
              </Body>
            </div>
          ))}
        </div>

        <div style={{ position: "absolute", left: 0, right: 0, bottom: 200, display: "flex", flexDirection: "column", alignItems: "center" }}>
          <Display size={112} style={{ textAlign: "center", fontStyle: "italic" }}>Box of</Display>
          <Display size={112} style={{ textAlign: "center", marginTop: 10, marginBottom: 72 }}>radiant moments</Display>
          <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 22, animation: reduced ? "none" : "kerai-breathe 3.4s ease-in-out infinite" }}>
            <div style={{ width: 80, height: 80, borderRadius: "50%", border: `1.5px solid ${t.gold}`, display: "flex", alignItems: "center", justifyContent: "center" }}>
              <div style={{ width: 14, height: 14, borderRadius: "50%", background: t.gold }} />
            </div>
            <Eyebrow style={{ color: t.fg }}>Tap to begin</Eyebrow>
          </div>
        </div>
      </div>

      <style>{`
        @keyframes kerai-breathe {
          0%, 100% { opacity: 0.72; transform: translateY(0); }
          50% { opacity: 1; transform: translateY(-6px); }
        }
      `}</style>
    </ScreenFrame>
  );
}

/* ------------------------------------------------------------------ */
/* 02. CHOOSE YOUR BOX                                                 */
/* The grid mirrors the cabinet's four lit boxes, so a guest can look  */
/* from a tile to the box beside them. Beneath: everything in the      */
/* machine, or the sets. Reviews take turns at the foot of the screen. */
/* ------------------------------------------------------------------ */
function BoxTile({ box, index, onPick, onLock, locked }) {
  const [filled, setFilled] = useState(false);
  const ink = PALETTE.orange;

  const choose = () => {
    if (locked || filled) return;
    setFilled(true);
    if (onLock) onLock();
    window.setTimeout(() => onPick(box.id), 720);
  };

  return (
    <div style={{ opacity: 0, animation: `kerai-tile-in 0.9s ${EASE_A} ${0.15 + index * 0.08}s forwards` }}>
      <button
        onClick={choose}
        aria-label={`Box ${box.id}, ${box.name}`}
        style={{
          position: "relative", display: "flex", alignItems: "center", justifyContent: "center",
          width: "100%", height: "100%", overflow: "hidden", padding: 0,
          cursor: locked && !filled ? "default" : "pointer",
          background: "transparent", border: `2px solid ${ink}`,
          transform: filled ? "scale(0.97)" : "scale(1)",
          transition: `transform 0.45s ${EASE_A}`,
        }}
      >
        <div style={{
          position: "absolute", inset: 0, background: ink,
          transform: filled ? "scale(1)" : "scale(0)", transformOrigin: "center",
          transition: `transform 0.5s ${EASE_A}`, pointerEvents: "none",
        }} />
        <Display size={104} style={{ position: "relative", color: filled ? PALETTE.ivory : ink, fontStyle: "italic", lineHeight: 1, transition: "color 0.35s 0.08s" }}>
          {box.id}
        </Display>
      </button>
    </div>
  );
}

function Stars({ size = 30, color }) {
  return (
    <div style={{ display: "flex", gap: 10 }} aria-label="Five stars">
      {[0, 1, 2, 3, 4].map((i) => (
        <svg key={i} width={size} height={size} viewBox="0 0 24 24" aria-hidden="true">
          <path fill={color} d="M12 2.6 14.8 8.6 21.4 9.4 16.5 13.9 17.8 20.4 12 17.1 6.2 20.4 7.5 13.9 2.6 9.4 9.2 8.6Z" />
        </svg>
      ))}
    </div>
  );
}

function Reviews({ reviews }) {
  const t = themeTokens(useTheme());
  const reduced = useReducedMotion();
  const idx = useTurns(reviews.length, 6500, reduced);
  return (
    <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 30 }}>
      <Stars color={PALETTE.orange} />
      <div style={{ position: "relative", width: 900, height: 190 }} aria-live="polite">
        {reviews.map((r, i) => (
          <figure key={r.name} aria-hidden={i !== idx} style={{
            ...turnStyle(i === idx, reduced), margin: 0,
            display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "flex-start", gap: 22, textAlign: "center",
          }}>
            <blockquote style={{ margin: 0, fontFamily: SERIF, fontStyle: "italic", fontSize: 48, lineHeight: 1.18, color: t.fg, textWrap: "balance" }}>
              “{r.quote}”
            </blockquote>
            <figcaption style={{ ...TYPE.small, color: t.fgMuted }}>— {r.name}</figcaption>
          </figure>
        ))}
      </div>
    </div>
  );
}

function ScreenHome({ theme, onPickBox, onAllProducts, onSets, onLogo }) {
  const t = themeTokens(theme);
  const [picked, setPicked] = useState(null);
  const TILE = 252;
  const GAP = 20;
  const GRID = TILE * 2 + GAP;
  const enter = (delay) => ({ opacity: 0, animation: `kerai-tile-in 0.9s ${EASE_A} ${delay}s forwards` });

  return (
    <ScreenFrame theme={theme}>
      <div onClick={onLogo} style={{ position: "absolute", top: 0, height: 230, left: 0, right: 0, display: "flex", alignItems: "center", justifyContent: "center", zIndex: 10, cursor: "pointer" }}>
        <KeraiMark size={80} color={t.fg} />
      </div>

      <div style={{ position: "absolute", top: 300, left: 0, right: 0, display: "flex", flexDirection: "column", alignItems: "center" }}>
        <div style={{ textAlign: "center", marginBottom: 64, ...enter(0.05) }}>
          <Display size={104} style={{ fontStyle: "italic", marginBottom: 12 }}>Choose</Display>
          <Display size={104}>your box</Display>
        </div>

        <div style={{ width: GRID, height: GRID, display: "grid", gridTemplateColumns: "1fr 1fr", gridTemplateRows: "1fr 1fr", gap: GAP }}>
          {KA.BOXES.map((b, i) => (
            <BoxTile key={b.id} box={b} index={i} onPick={onPickBox} onLock={() => setPicked(b.id)} locked={picked !== null} />
          ))}
        </div>

        <div style={{ width: 720, marginTop: 56, display: "flex", flexDirection: "column", gap: 18, ...enter(0.5) }}>
          <div style={{ display: "flex", alignItems: "center", gap: 24, marginBottom: 14 }} aria-hidden="true">
            <div style={{ flex: 1, height: 1, background: t.line }} />
            <span style={{ fontFamily: SERIF, fontStyle: "italic", fontSize: 32, color: t.fgMuted, lineHeight: 1 }}>or</span>
            <div style={{ flex: 1, height: 1, background: t.line }} />
          </div>
          <PrimaryButton variant="ghost" onClick={onAllProducts}>See all products</PrimaryButton>
          <PrimaryButton variant="ghost" onClick={onSets}>Discover our sets</PrimaryButton>
        </div>
      </div>

      <div style={{ position: "absolute", left: 0, right: 0, bottom: 72, display: "flex", justifyContent: "center", ...enter(0.8) }}>
        <Reviews reviews={KA.REVIEWS} />
      </div>

      <style>{`
        @keyframes kerai-tile-in {
          0%   { opacity: 0; transform: translateY(28px) scale(0.985); filter: blur(6px); }
          60%  { filter: blur(0); }
          100% { opacity: 1; transform: translateY(0) scale(1); filter: blur(0); }
        }
      `}</style>
    </ScreenFrame>
  );
}

window.ScreenAttract = ScreenAttract;
window.ScreenHome = ScreenHome;
window.titledName = titledName;
