/* CRYSTAL BALL — controlled. The host (App) owns `revealed`
   and passes it down with onToggle. When pressed, the whole
   site shifts to mystical purple — handled by App at the body level.
   Mist gradient colors are CSS custom properties so they shift
   along with the rest of the page. */

const { useState: useStateB, useEffect: useEffectB, useRef: useRefB, useCallback: useCallbackB, useMemo: useMemoB } = React;

function drinkOfTheDay() {
  const cast = window.CAST || [];
  if (!cast.length) return null;
  const today = new Date();
  const seed =
    today.getFullYear() * 372 +
    (today.getMonth() + 1) * 31 +
    today.getDate();
  return cast[seed % cast.length];
}

const CrystalBall = ({ revealed, onToggle, lang = "en" }) => {
  const [pressing, setPressing] = useStateB(false);
  const drink = useMemoB(() => drinkOfTheDay(), []);

  const handleDown = () => setPressing(true);
  const handleUp = () => setPressing(false);

  const onKey = (e) => {
    if (e.key === "Enter" || e.key === " ") {
      e.preventDefault();
      onToggle();
    }
  };

  return (
    <div className="ball-wrap" style={{
      position: "relative",
      width: "100%",
      display: "flex",
      flexDirection: "column",
      alignItems: "center",
    }}>
      <button
        className={`crystal-ball${revealed ? " is-revealed" : ""}${pressing ? " is-pressing" : ""}`}
        onClick={onToggle}
        onKeyDown={onKey}
        onPointerDown={handleDown}
        onPointerUp={handleUp}
        onPointerLeave={handleUp}
        onPointerCancel={handleUp}
        aria-label="crystal ball"
        aria-pressed={revealed}
        style={{
          position: "relative",
          display: "block",
          padding: 0,
          background: "none",
          border: "none",
          cursor: "pointer",
          transform: pressing ? "scale(.985)" : "scale(1)",
          transition: "transform .22s cubic-bezier(.2,.7,.2,1)",
          width: "100%",
          outline: "none",
          WebkitTapHighlightColor: "transparent",
        }}
      >
        <div className="orb-breath" style={{ width: "100%" }}>
          <BallSVG revealed={revealed} drinkName={drink ? drink.name : ""} lang={lang} />
        </div>
      </button>

      {/* Revealed prompt — beneath the ball, only after press. */}
      <div
        className="ball-prompt"
        aria-live="polite"
        style={{
          marginTop: "clamp(14px, 1.4vw, 22px)",
          opacity: revealed ? 1 : 0,
          transform: `translateY(${revealed ? 0 : 10}px)`,
          transition: "opacity .65s ease .55s, transform .7s cubic-bezier(.2,.7,.2,1) .55s",
          pointerEvents: revealed ? "auto" : "none",
          width: "min(440px, 92vw)",
          textAlign: "center",
        }}
      >
        <div style={{
          display: "inline-flex",
          alignItems: "center",
          gap: 10,
          color: "var(--gold)",
          fontStyle: "italic",
          fontSize: 13,
          letterSpacing: ".18em",
          textTransform: "uppercase",
          transition: "color 1.2s ease",
        }}>
          <span style={{
            display: "inline-block", width: 24, height: 1,
            background: "currentColor", opacity: .8,
          }}/>
          {window.t ? window.t("ball.prompt.eyebrow", lang) : "today's pour"}
          <span style={{
            display: "inline-block", width: 24, height: 1,
            background: "currentColor", opacity: .8,
          }}/>
        </div>
        <p style={{
          marginTop: 12,
          fontStyle: "italic",
          color: "var(--ink-soft)",
          fontSize: 15.5,
          lineHeight: 1.55,
          transition: "color 1.2s ease",
        }}>
          {window.t ? window.t("ball.prompt.line1.pre", lang) : "Bring this with you for"}{" "}
          <span style={{
            background: "color-mix(in oklab, var(--gold) 22%, transparent)",
            padding: "0 6px",
            borderRadius: 2,
            color: "var(--ink)",
            fontStyle: "normal",
            fontFamily: "var(--display)",
            transition: "background-color 1.2s ease, color 1.2s ease",
          }}>{window.t ? window.t("ball.prompt.placeholder", lang) : "[ placeholder · daily reward ]"}</span>.
          <br/>
          {window.t ? window.t("ball.prompt.line2", lang) : "Show your barista — today only."}
        </p>
      </div>
    </div>
  );
};

/* ----- The SVG ball itself.
   Mist gradient colors reference CSS vars so they shift
   with the page palette in mystic mode. ----- */
const BallSVG = ({ revealed, drinkName, lang = "en" }) => {
  const W = 480, H = 480;
  const cx = 240, cy = 210, r = 180;

  return (
    <svg
      viewBox={`0 0 ${W} ${H}`}
      style={{ width: "100%", height: "auto", overflow: "visible", display: "block" }}
      role="img"
      aria-hidden="true"
    >
      <defs>
        {/* glass body — pale, cool, mostly transparent */}
        <radialGradient id="glassBody" cx=".5" cy=".5" r=".5">
          <stop offset="0%"   style={{stopColor:"var(--glass-1, rgba(255,255,255,.18))"}} />
          <stop offset="55%"  style={{stopColor:"var(--glass-2, rgba(199,207,219,.16))"}} />
          <stop offset="88%"  style={{stopColor:"var(--glass-3, rgba(142,151,166,.30))"}} />
          <stop offset="100%" style={{stopColor:"var(--glass-4, rgba(74,58,44,.46))"}} />
        </radialGradient>
        {/* outer rim darkening — refraction */}
        <radialGradient id="glassRim" cx=".5" cy=".5" r=".5">
          <stop offset="78%"  stopColor="rgba(0,0,0,0)" />
          <stop offset="98%"  style={{stopColor:"var(--glass-rim, rgba(28,20,14,.35))"}} />
          <stop offset="100%" style={{stopColor:"var(--glass-rim2, rgba(28,20,14,.55))"}} />
        </radialGradient>
        {/* upper specular highlight */}
        <radialGradient id="glassHi" cx=".3" cy=".22" r=".24">
          <stop offset="0%"   stopColor="rgba(255,255,255,.85)" />
          <stop offset="60%"  stopColor="rgba(255,255,255,.18)" />
          <stop offset="100%" stopColor="rgba(255,255,255,0)" />
        </radialGradient>
        {/* lower bounce light */}
        <radialGradient id="glassBounce" cx=".68" cy=".82" r=".22">
          <stop offset="0%"   style={{stopColor:"var(--glass-bounce, rgba(244,236,222,.55))"}} />
          <stop offset="100%" stopColor="rgba(0,0,0,0)" />
        </radialGradient>
        {/* mist gradients — colors via CSS vars */}
        <radialGradient id="mistGrad1" cx=".5" cy=".5" r=".5">
          <stop offset="0%"   style={{stopColor:"var(--mist-1, rgba(255,255,255,.95))"}} />
          <stop offset="55%"  style={{stopColor:"var(--mist-2, rgba(244,236,222,.55))"}} />
          <stop offset="100%" style={{stopColor:"var(--mist-2-edge, rgba(244,236,222,0))"}} />
        </radialGradient>
        <radialGradient id="mistGrad2" cx=".5" cy=".5" r=".5">
          <stop offset="0%"   style={{stopColor:"var(--mist-3, rgba(232,221,196,.85))"}} />
          <stop offset="60%"  style={{stopColor:"var(--mist-4, rgba(199,207,219,.30))"}} />
          <stop offset="100%" style={{stopColor:"var(--mist-4-edge, rgba(199,207,219,0))"}} />
        </radialGradient>
        <radialGradient id="mistGrad3" cx=".5" cy=".5" r=".5">
          <stop offset="0%"   style={{stopColor:"var(--mist-5, rgba(255,250,235,.80))"}} />
          <stop offset="70%"  style={{stopColor:"var(--mist-6, rgba(255,250,235,.18))"}} />
          <stop offset="100%" style={{stopColor:"var(--mist-6-edge, rgba(255,250,235,0))"}} />
        </radialGradient>
        {/* shadow under the ball */}
        <radialGradient id="ballShadow" cx=".5" cy=".5" r=".5">
          <stop offset="0%"   style={{stopColor:"var(--ball-shadow, rgba(28,20,14,.42))"}} />
          <stop offset="100%" stopColor="rgba(0,0,0,0)" />
        </radialGradient>
        {/* base / ring stand */}
        <linearGradient id="standBody" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%"   stopColor="#3a2818" />
          <stop offset="60%"  stopColor="#231507" />
          <stop offset="100%" stopColor="#120a04" />
        </linearGradient>
        <linearGradient id="standBrass" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%"   stopColor="#d4b889" />
          <stop offset="50%"  stopColor="#b89254" />
          <stop offset="100%" stopColor="#8a6a3c" />
        </linearGradient>

        <clipPath id="ballClip">
          <circle cx={cx} cy={cy} r={r - 2} />
        </clipPath>
      </defs>

      {/* ground shadow */}
      <ellipse cx={cx} cy={cy + r + 38} rx={r * .95} ry="12" fill="url(#ballShadow)" />

      {/* base / stand */}
      <g>
        <ellipse cx={cx} cy={cy + r + 14} rx={r * .70} ry="16" fill="url(#standBody)" />
        <ellipse cx={cx} cy={cy + r + 12} rx={r * .68} ry="13" fill="#2a1a0c" />
        <ellipse cx={cx} cy={cy + r + 5}  rx={r * .54} ry="10" fill="url(#standBrass)" />
        <ellipse cx={cx} cy={cy + r + 3}  rx={r * .50} ry="7"  fill="#8a6a3c" />
        {[-1, 0, 1].map((i) => (
          <rect key={i}
            x={cx + i * (r * .45) - 3.5}
            y={cy + r + 16}
            width="7" height="12"
            rx="1.5"
            fill="#8a6a3c"
          />
        ))}
      </g>

      {/* the glass sphere */}
      <g>
        <circle cx={cx} cy={cy} r={r} fill="url(#glassBody)" />

        {/* mist inside, only when revealed */}
        <g clipPath="url(#ballClip)" style={{
          opacity: revealed ? 1 : 0,
          transition: "opacity 1.05s ease",
        }}>
          <circle cx={cx} cy={cy} r={r - 4} fill="var(--mist-wash, rgba(244,236,222,.20))" style={{transition:"fill 1.2s ease"}}/>

          <g style={{
            transformOrigin: `${cx}px ${cy}px`,
            animation: revealed ? "mistSwirl 22s linear infinite" : "none",
          }}>
            <ellipse cx={cx - 40} cy={cy + 14} rx="138" ry="82" fill="url(#mistGrad1)" opacity=".72" />
            <ellipse cx={cx + 48} cy={cy - 28} rx="110" ry="76" fill="url(#mistGrad2)" opacity=".66" />
          </g>
          <g style={{
            transformOrigin: `${cx}px ${cy}px`,
            animation: revealed ? "mistSwirl 34s linear infinite reverse" : "none",
          }}>
            <ellipse cx={cx + 28} cy={cy + 40} rx="124" ry="66" fill="url(#mistGrad3)" opacity=".55" />
            <ellipse cx={cx - 55} cy={cy - 40} rx="96"  ry="60" fill="url(#mistGrad1)" opacity=".50" />
          </g>
          <g style={{
            transformOrigin: `${cx}px ${cy}px`,
            animation: revealed ? "mistDrift 9s ease-in-out infinite" : "none",
          }}>
            <ellipse cx={cx} cy={cy + 8} rx="150" ry="50" fill="url(#mistGrad2)" opacity=".40" />
          </g>

          {/* drink reveal text */}
          <g style={{
            opacity: revealed ? 1 : 0,
            transform: revealed ? `translateY(0px)` : `translateY(24px)`,
            transformOrigin: `${cx}px ${cy}px`,
            transition: "opacity .9s ease .55s, transform 1.1s cubic-bezier(.2,.7,.2,1) .55s",
          }}>
            <text
              x={cx}
              y={cy - 32}
              textAnchor="middle"
              fontFamily="Cormorant Garamond, serif"
              fontStyle="italic"
              fontSize="15"
              letterSpacing="3.5"
              style={{fill:"var(--reveal-eyebrow, rgba(28,20,14,.55))", transition:"fill 1.2s ease"}}
            >{window.t ? window.t("ball.today", lang) : "TODAY"}</text>
            <text
              x={cx}
              y={cy + 14}
              textAnchor="middle"
              fontFamily="Italiana, serif"
              fontSize={drinkName.length > 14 ? 32 : drinkName.length > 10 ? 38 : 44}
              style={{fill:"var(--reveal-title, rgba(28,20,14,.92))", transition:"fill 1.2s ease"}}
            >{drinkName}</text>
            <line
              x1={cx - 40} y1={cy + 36}
              x2={cx + 40} y2={cy + 36}
              strokeWidth="1"
              opacity=".85"
              style={{stroke:"var(--reveal-rule, #b89254)", transition:"stroke 1.2s ease"}}
            />
            <text
              x={cx}
              y={cy + 60}
              textAnchor="middle"
              fontFamily="Cormorant Garamond, serif"
              fontStyle="italic"
              fontSize="16"
              style={{fill:"var(--reveal-sub, rgba(74,58,44,.7))", transition:"fill 1.2s ease"}}
            >{window.t ? window.t("ball.tagline", lang) : "a fortune in a cup"}</text>
          </g>
        </g>

        {/* rim refraction */}
        <circle cx={cx} cy={cy} r={r} fill="url(#glassRim)" />
        {/* outer hairline */}
        <circle cx={cx} cy={cy} r={r}
          fill="none"
          strokeWidth="1"
          style={{stroke:"var(--ball-hairline, rgba(28,20,14,.35))", transition:"stroke 1.2s ease"}}
        />

        {/* bounce light */}
        <ellipse cx={cx + 52} cy={cy + 64} rx="54" ry="30" fill="url(#glassBounce)" opacity=".7" />

        {/* specular highlight */}
        <ellipse cx={cx - 52} cy={cy - 76} rx="46" ry="26" fill="url(#glassHi)" />
        <ellipse cx={cx - 70} cy={cy - 96} rx="8" ry="4.5" fill="rgba(255,255,255,.95)" />
      </g>
    </svg>
  );
};

Object.assign(window, { CrystalBall });
