/* PRAXIA — Video components
   PraxiaVideo: editorial player with brass poster, plays on click.
   PraxiaVideoBanner: larger framed variant for Home (Welcome) and Preview surfaces.

   Source: Supabase Storage public bucket. URLs assembled in data.jsx via PRAXIA_COURSE.media.
*/

function PraxiaVideo({ src, title, eyebrow, posterText, tokens, variant = "module" }) {
  const [started, setStarted] = React.useState(false);
  const [error, setError] = React.useState(null);
  const videoRef = React.useRef(null);

  if (!src) return null;

  // Play synchronously inside the user gesture — setTimeout breaks the gesture
  // context in some browsers and silently rejects the play() promise.
  const handlePlay = () => {
    const v = videoRef.current;
    if (!v) return;
    setStarted(true);
    const p = v.play();
    if (p && typeof p.catch === "function") {
      p.catch((err) => {
        console.error("[PraxiaVideo] play() rejected:", err);
        setError(err?.message || String(err));
      });
    }
  };

  const handleVideoError = () => {
    const v = videoRef.current;
    const err = v?.error;
    console.error("[PraxiaVideo] <video> error", { code: err?.code, message: err?.message, src });
    setError(`Video failed to load (code ${err?.code ?? "?"})`);
  };

  const isBanner = variant === "banner";
  const radius = isBanner ? 4 : 2;

  return (
    <figure style={{
      margin: isBanner ? "0 0 56px 0" : "0 0 40px 0",
      border: `1px solid ${tokens.line}`,
      borderRadius: radius,
      overflow: "hidden",
      background: tokens.surface,
      boxShadow: `0 24px 60px -20px color-mix(in srgb, ${tokens.bg} 80%, transparent)`,
    }}>
      {(eyebrow || title) && (
        <figcaption style={{
          padding: "16px 24px",
          background: tokens.surface2,
          borderBottom: `1px solid ${tokens.line}`,
          display: "flex",
          alignItems: "baseline",
          justifyContent: "space-between",
          gap: 16,
        }}>
          <div style={{ display: "flex", alignItems: "baseline", gap: 16, minWidth: 0 }}>
            {eyebrow && (
              <span className="mono" style={{ color: tokens.accent, whiteSpace: "nowrap" }}>
                {eyebrow}
              </span>
            )}
            {title && (
              <span className="display" style={{
                fontStyle: "italic",
                fontSize: 18,
                color: tokens.text,
                overflow: "hidden",
                textOverflow: "ellipsis",
                whiteSpace: "nowrap",
              }}>
                {title}
              </span>
            )}
          </div>
          <span className="mono" style={{ color: tokens.mute, whiteSpace: "nowrap" }}>
            Watch
          </span>
        </figcaption>
      )}

      <div style={{ position: "relative", aspectRatio: "16/9", background: tokens.bg }}>
        <video
          ref={videoRef}
          src={src}
          controls={started}
          preload="metadata"
          playsInline
          style={{ width: "100%", height: "100%", display: "block", objectFit: "contain", background: tokens.bg }}
          onPlay={() => setStarted(true)}
          onError={handleVideoError}
        />

        {error && (
          <div style={{
            position: "absolute", left: 16, right: 16, bottom: 16,
            padding: "10px 14px",
            background: "rgba(180, 60, 50, 0.95)",
            color: "white",
            fontFamily: "var(--mono)",
            fontSize: 12,
            borderRadius: 2,
            zIndex: 3,
          }}>
            {error} — check browser console for details.
          </div>
        )}

        {!started && (
          <button
            onClick={handlePlay}
            aria-label={title ? `Play: ${title}` : "Play video"}
            style={{
              position: "absolute", inset: 0,
              border: "none",
              cursor: "pointer",
              padding: 0,
              background: `
                radial-gradient(60% 50% at 50% 50%, color-mix(in srgb, ${tokens.accent} 14%, transparent) 0%, transparent 70%),
                linear-gradient(180deg, color-mix(in srgb, ${tokens.bg2} 70%, transparent) 0%, color-mix(in srgb, ${tokens.bg} 85%, transparent) 100%)
              `,
              display: "flex",
              flexDirection: "column",
              alignItems: "center",
              justifyContent: "center",
              gap: 22,
              color: tokens.text,
            }}
          >
            <div style={{
              width: 84, height: 84, borderRadius: "50%",
              background: `linear-gradient(135deg, ${tokens.accent}, ${tokens.accent2})`,
              border: `1px solid color-mix(in srgb, ${tokens.accent} 60%, ${tokens.bg})`,
              display: "flex", alignItems: "center", justifyContent: "center",
              boxShadow: `0 14px 40px -10px color-mix(in srgb, ${tokens.accent} 55%, transparent)`,
              transition: "transform .25s ease",
            }}>
              <svg width="26" height="26" viewBox="0 0 24 24" fill="none" style={{ marginLeft: 3 }}>
                <path d="M8 5l11 7-11 7V5z" fill={tokens.bg} />
              </svg>
            </div>
            {posterText && (
              <p style={{
                margin: 0,
                fontFamily: "var(--display)",
                fontStyle: "italic",
                fontSize: 17,
                lineHeight: 1.5,
                color: tokens.soft,
                textAlign: "center",
                maxWidth: 460,
                padding: "0 24px",
              }}>
                {posterText}
              </p>
            )}
          </button>
        )}
      </div>
    </figure>
  );
}

window.PraxiaVideo = PraxiaVideo;
