/* Sosh Insider — Bali :: desktop, menu bar, chapter cards, main window */

/* ---------- live clock ---------- */
function Clock() {
  const [now, setNow] = useState(new Date());
  useEffect(() => {
    const t = setInterval(() => setNow(new Date()), 1000);
    return () => clearInterval(t);
  }, []);
  let h = now.getHours();
  const ampm = h >= 12 ? "PM" : "AM";
  h = h % 12 || 12;
  const m = String(now.getMinutes()).padStart(2, "0");
  return (
    <span className="mono" style={{ fontSize: 16, lineHeight: 1, letterSpacing: 0.5 }}>
      {h}:{m} {ampm}
    </span>
  );
}

/* ---------- top menu bar ---------- */
function MenuBar({ musicOn, onToggleMusic, onAbout, onResetIcons }) {
  const [open, setOpen] = useState(null);
  const menus = {
    "\u25C8": [
      { label: "About Sosh Insider…", fn: onAbout },
      { label: "—" },
      { label: "Sound: " + (window.SFX ? "On" : "Off"), fn: () => {} },
    ],
    File: [
      { label: "New Roll  ⌘N", fn: () => {} },
      { label: "Import Photos…", fn: () => {} },
      { label: "—" },
      { label: "Print Contact Sheet", fn: () => window.print() },
    ],
    View: [
      { label: "by Chapter ✓", fn: () => {} },
      { label: "by Date", fn: () => {} },
      { label: "—" },
      { label: "Clean Up Desktop", fn: onResetIcons },
    ],
    Special: [
      { label: "Shuffle the Deck", fn: () => {} },
      { label: "Empty Trash", fn: () => {} },
    ],
  };

  const item = (name) => (
    <div
      key={name}
      data-clickable
      onMouseDown={(e) => {
        e.stopPropagation();
        window.SFX && SFX.click();
        setOpen(open === name ? null : name);
      }}
      onMouseEnter={() => open && setOpen(name)}
      style={{
        padding: "0 9px",
        height: "100%",
        display: "flex",
        alignItems: "center",
        fontSize: name.length === 1 ? 13 : 9,
        background: open === name ? "var(--ink)" : "transparent",
        color: open === name ? "var(--paper)" : "var(--ink)",
        position: "relative",
      }}
    >
      {name}
      {open === name && (
        <div
          className="win"
          style={{
            position: "absolute",
            top: "100%",
            left: 0,
            minWidth: 178,
            padding: 3,
            boxShadow: "4px 4px 0 rgba(43,38,34,0.3)",
            zIndex: 200,
          }}
        >
          {menus[name].map((mi, i) =>
            mi.label === "—" ? (
              <div key={i} style={{ borderTop: "1px solid rgba(43,38,34,0.3)", margin: "3px 2px" }} />
            ) : (
              <div
                key={i}
                data-clickable
                onMouseDown={(e) => {
                  e.stopPropagation();
                  window.SFX && SFX.click();
                  setOpen(null);
                  mi.fn && mi.fn();
                }}
                className="pixel"
                style={{ fontSize: 8.5, padding: "5px 8px", color: "var(--ink)" }}
                onMouseEnter={(e) => {
                  e.currentTarget.style.background = "var(--ink)";
                  e.currentTarget.style.color = "var(--paper)";
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.background = "transparent";
                  e.currentTarget.style.color = "var(--ink)";
                }}
              >
                {mi.label}
              </div>
            )
          )}
        </div>
      )}
    </div>
  );

  return (
    <div
      onMouseLeave={() => setOpen(null)}
      style={{
        position: "fixed",
        top: 0,
        left: 0,
        right: 0,
        height: 24,
        background: "var(--paper)",
        borderBottom: "2px solid var(--line)",
        display: "flex",
        alignItems: "center",
        zIndex: 1000,
        fontFamily: "var(--pixel)",
        boxShadow: "0 2px 0 rgba(43,38,34,0.12)",
      }}
    >
      {["\u25C8"].map(item)}
      <div
        className="pixel"
        style={{ padding: "0 10px 0 2px", fontSize: 9, fontWeight: 700, display: "flex", alignItems: "center", height: "100%" }}
      >
        Sosh Insider
      </div>
      {["File", "View", "Special"].map(item)}
      <div style={{ flex: 1 }} />
      <div
        data-clickable
        title="Music"
        onMouseDown={(e) => {
          e.stopPropagation();
          onToggleMusic();
        }}
        style={{
          padding: "0 10px",
          height: "100%",
          display: "flex",
          alignItems: "center",
          gap: 5,
          fontSize: 12,
          background: musicOn ? "var(--ink)" : "transparent",
          color: musicOn ? "var(--paper)" : "var(--ink)",
        }}
      >
        <span style={{ fontSize: 13 }}>{musicOn ? "♪" : "♪"}</span>
        <span style={{ fontSize: 8 }} className="pixel">
          {musicOn ? "ON" : "OFF"}
        </span>
      </div>
      <div style={{ padding: "0 12px 0 8px", display: "flex", alignItems: "center", height: "100%", borderLeft: "1px solid rgba(43,38,34,0.25)" }}>
        <Clock />
      </div>
    </div>
  );
}

/* ---------- chapter card (3 variants via tweak) ---------- */
function ChapterCard({ chapter, variant, index, onOpen }) {
  const [hover, setHover] = useState(false);
  const isVideo = chapter.kind === "video";
  const hero = isVideo ? null : chapter.frames[0];
  const lift = hover ? "translate(-1px,-2px)" : "translate(0,0)";
  const shadow = hover
    ? "5px 6px 0 rgba(43,38,34,0.34)"
    : "3px 3px 0 rgba(43,38,34,0.26)";

  const open = () => {
    window.SFX && SFX.open();
    onOpen(chapter);
  };

  /* locked album — sealed until its unlock date */
  if (chapter.locked) {
    return (
      <div
        data-clickable
        onClick={open}
        onMouseEnter={() => setHover(true)}
        onMouseLeave={() => setHover(false)}
        title={"Unlocks " + chapter.unlockLabel}
        style={{
          background: "var(--paper2)",
          border: "2px solid var(--line)",
          transform: lift,
          boxShadow: shadow,
          transition: "transform 0.12s, box-shadow 0.12s",
          overflow: "hidden",
        }}
      >
        <div
          style={{
            position: "relative",
            aspectRatio: "4 / 3",
            borderBottom: "2px solid var(--line)",
            background:
              "repeating-linear-gradient(45deg, rgba(43,38,34,0.07) 0 10px, transparent 10px 20px), " +
              hexA(chapter.tint, 0.12),
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            flexDirection: "column",
            gap: 8,
            color: "var(--ink-soft)",
          }}
        >
          <svg width="34" height="40" viewBox="0 0 34 40" shapeRendering="crispEdges">
            <rect x="5" y="17" width="24" height="20" fill="var(--paper)" stroke="#2b2622" strokeWidth="2" />
            <path d="M9 17 v-5 a8 8 0 0 1 16 0 v5" fill="none" stroke="#2b2622" strokeWidth="2" />
            <rect x="15" y="24" width="4" height="7" fill="#2b2622" />
          </svg>
          <div className="pixel" style={{ fontSize: 8, textTransform: "uppercase", letterSpacing: 0.5 }}>
            Locked
          </div>
        </div>
        <div style={{ padding: 10, display: "flex", flexDirection: "column", gap: 4 }}>
          <div className="pixel" style={{ fontSize: 9.5, textTransform: "uppercase" }}>{chapter.title}</div>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 8 }}>
            <span className="mono" style={{ fontSize: 13, color: "var(--ink-soft)" }}>{chapter.roll}</span>
            <span className="mono" style={{ fontSize: 12, color: "#fff", background: "var(--ink)", padding: "1px 6px", whiteSpace: "nowrap" }}>
              ⌛ {chapter.unlockLabel}
            </span>
          </div>
        </div>
      </div>
    );
  }

  /* unlocked but no frames loaded yet — gentle "developing" card */
  if (!isVideo && !hero) {
    return (
      <div
        data-clickable
        onClick={open}
        onMouseEnter={() => setHover(true)}
        onMouseLeave={() => setHover(false)}
        style={{
          background: "var(--paper)",
          border: "2px solid var(--line)",
          transform: lift,
          boxShadow: shadow,
          transition: "transform 0.12s, box-shadow 0.12s",
          overflow: "hidden",
        }}
      >
        <div
          style={{
            position: "relative",
            aspectRatio: "4 / 3",
            borderBottom: "2px solid var(--line)",
            background:
              "repeating-linear-gradient(135deg, rgba(43,38,34,0.05) 0 7px, transparent 7px 14px), " +
              hexA(chapter.tint, 0.1),
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            color: "var(--ink-soft)",
          }}
        >
          <span className="mono" style={{ fontSize: 13 }}>developing…</span>
        </div>
        <div style={{ padding: 10 }}>
          <div className="pixel" style={{ fontSize: 9.5, textTransform: "uppercase" }}>{chapter.title}</div>
          <div className="mono" style={{ fontSize: 12.5, color: "var(--ink-soft)", marginTop: 3 }}>{chapter.roll} · awaiting frames</div>
        </div>
      </div>
    );
  }

  /* video album card — reads like a tape on the shelf */
  if (isVideo) {
    return (
      <div
        data-clickable
        onClick={open}
        onMouseEnter={() => setHover(true)}
        onMouseLeave={() => setHover(false)}
        style={{
          background: "#2b2622",
          border: "2px solid var(--line)",
          transform: lift,
          boxShadow: shadow,
          transition: "transform 0.12s, box-shadow 0.12s",
          overflow: "hidden",
        }}
      >
        <div style={{ position: "relative", aspectRatio: "16 / 11", borderBottom: "2px solid var(--line)" }}>
          <VideoScreen clip={chapter.videos[0]} playing={hover} tint={chapter.tint} />
          <div style={{ position: "absolute", top: 7, left: 8 }}>
            <SoshTVMark small />
          </div>
          <div className="mono" style={{ position: "absolute", top: 8, right: 8, background: "#d23b2e", color: "#fff", fontSize: 11, padding: "0 5px" }}>
            ● VIDEO
          </div>
          <div style={{ position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center" }}>
            <div style={{ width: 42, height: 42, border: "2px solid rgba(255,255,255,0.9)", background: "rgba(20,16,13,0.3)", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 16 }}>
              {hover ? "❚❚" : "▶"}
            </div>
          </div>
        </div>
        <div style={{ padding: 10, display: "flex", flexDirection: "column", gap: 4, background: "var(--paper)" }}>
          <div className="pixel" style={{ fontSize: 9.5, textTransform: "uppercase" }}>{chapter.title}</div>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 8 }}>
            <span className="mono" style={{ fontSize: 13, color: "var(--ink-soft)" }}>{chapter.place}</span>
            <span className="mono" style={{ fontSize: 12, color: "#fff", background: "var(--terracotta)", padding: "1px 6px", whiteSpace: "nowrap", flex: "0 0 auto" }}>
              {chapter.count} clips +{chapter.driveCount}
            </span>
          </div>
        </div>
      </div>
    );
  }

  /* shared meta block */
  const Meta = ({ pad = 10 }) => (
    <div style={{ padding: pad, display: "flex", flexDirection: "column", gap: 4 }}>
      <div
        className="pixel"
        style={{ fontSize: 9.5, lineHeight: 1.3, textTransform: "uppercase", color: "var(--ink)" }}
      >
        {chapter.title}
      </div>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 8 }}>
        <span className="mono" style={{ fontSize: 13, color: "var(--ink-soft)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", minWidth: 0 }}>
          {chapter.place}
        </span>
        <span
          className="mono"
          style={{
            fontSize: 12,
            color: "#fff",
            background: "var(--ink)",
            padding: "1px 6px",
            whiteSpace: "nowrap",
            flex: "0 0 auto",
          }}
        >
          {chapter.count} frames
        </span>
      </div>
    </div>
  );

  if (variant === "polaroid") {
    return (
      <div
        data-clickable
        onClick={open}
        onMouseEnter={() => setHover(true)}
        onMouseLeave={() => setHover(false)}
        style={{
          background: "var(--paper)",
          border: "2px solid var(--line)",
          padding: 9,
          paddingBottom: 6,
          transform: lift + (hover ? " rotate(-0.6deg)" : ` rotate(${index % 2 ? 0.5 : -0.4}deg)`),
          boxShadow: shadow,
          transition: "transform 0.12s, box-shadow 0.12s",
        }}
      >
        <PhotoPlaceholder frame={hero} tint={chapter.tint} />
        <div style={{ paddingTop: 9, textAlign: "center" }}>
          <div className="serif" style={{ fontSize: 18, fontStyle: "italic", lineHeight: 1.1 }}>
            {chapter.title}
          </div>
          <div className="mono" style={{ fontSize: 12.5, color: "var(--ink-soft)", marginTop: 3 }}>
            {chapter.roll} · {chapter.count} frames
          </div>
        </div>
      </div>
    );
  }

  if (variant === "filmstrip") {
    return (
      <div
        data-clickable
        onClick={open}
        onMouseEnter={() => setHover(true)}
        onMouseLeave={() => setHover(false)}
        style={{
          background: "#2b2622",
          border: "2px solid var(--line)",
          padding: "7px 9px",
          transform: lift,
          boxShadow: shadow,
          transition: "transform 0.12s, box-shadow 0.12s",
        }}
      >
        <div className="mono" style={{ color: "#e7c98a", fontSize: 12, display: "flex", justifyContent: "space-between", padding: "0 2px 5px" }}>
          <span>{chapter.roll}</span>
          <span>{hover ? "▶ OPEN" : "KODAK 400"}</span>
        </div>
        <div style={{ display: "flex", gap: 4 }}>
          {chapter.frames.slice(0, 3).map((f, i) => (
            <div key={i} style={{ flex: i === 0 ? "1.6" : "1", minWidth: 0 }}>
              <PhotoPlaceholder frame={i === 0 ? hero : { ...f, ar: "1 / 1" }} tint={chapter.tint} />
            </div>
          ))}
        </div>
        <div style={{ background: "var(--paper)", margin: "6px -9px -7px", padding: "8px 10px", borderTop: "2px solid var(--line)" }}>
          <div className="pixel" style={{ fontSize: 9.5, textTransform: "uppercase" }}>{chapter.title}</div>
          <div className="mono" style={{ fontSize: 12.5, color: "var(--ink-soft)", marginTop: 2 }}>
            {chapter.place} — {chapter.count} frames
          </div>
        </div>
      </div>
    );
  }

  /* plain "icon view" card */
  return (
    <div
      data-clickable
      onClick={open}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        background: "var(--paper)",
        border: "2px solid var(--line)",
        transform: lift,
        boxShadow: shadow,
        transition: "transform 0.12s, box-shadow 0.12s",
        overflow: "hidden",
      }}
    >
      <div style={{ borderBottom: "2px solid var(--line)", position: "relative" }}>
        <PhotoPlaceholder frame={hero} tint={chapter.tint} />
        <div
          className="mono"
          style={{ position: "absolute", top: 6, left: 6, background: "var(--ink)", color: "#fff", fontSize: 11, padding: "0 5px" }}
        >
          {chapter.roll}
        </div>
        {hover && (
          <div
            className="pixel"
            style={{ position: "absolute", inset: 0, background: "rgba(43,38,34,0.55)", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 10, letterSpacing: 1 }}
          >
            ▶ OPEN ROLL
          </div>
        )}
      </div>
      <Meta />
    </div>
  );
}

window.MenuBar = MenuBar;
window.ChapterCard = ChapterCard;
window.Clock = Clock;
