/* global React */
const { useState, useRef } = React;

const SHOT_TYPES = ["WIDE", "MED", "CLOSE", "INSERT"];

const INIT_CELLS = [
  { id: 1, shot: "WIDE", text: "Open on the empty classroom. Morning light. No people yet.", dur: "0:04" },
  { id: 2, shot: "CLOSE", text: "Hands unpacking a worn notebook. Pages marked with sticky tabs.", dur: "0:03" },
  { id: 3, shot: "MED", text: "Narrator sets the scene: 'I didn't think I'd teach this class twice.'", dur: "0:06" },
  { id: 4, shot: "INSERT", text: "Archive photo: the first cohort, 2019. Faces a little younger.", dur: "0:03" },
  { id: 5, shot: "CLOSE", text: "A student's handwritten note, folded in half. Still in the notebook.", dur: "0:04" },
  { id: 6, shot: "WIDE", text: "The same room, full now. The turn of the story.", dur: "0:05" },
];

function ShotSketch({ type }) {
  const common = { width: "100%", height: "100%", preserveAspectRatio: "xMidYMid slice" };
  if (type === "WIDE") {
    return (
      <svg {...common} viewBox="0 0 160 100">
        <rect width="160" height="100" fill="var(--bg-2)"/>
        <rect x="0" y="60" width="160" height="40" fill="color-mix(in oklab, var(--ink) 6%, transparent)"/>
        <circle cx="40" cy="58" r="5" fill="var(--ink-mute)"/>
        <rect x="36" y="60" width="8" height="16" fill="var(--ink-mute)"/>
        <circle cx="120" cy="56" r="5" fill="var(--ink-dim)"/>
        <rect x="116" y="58" width="8" height="18" fill="var(--ink-dim)"/>
        <path d="M0 40 L50 30 L110 34 L160 28" stroke="var(--line-2)" strokeWidth="1" fill="none"/>
      </svg>
    );
  }
  if (type === "MED") {
    return (
      <svg {...common} viewBox="0 0 160 100">
        <rect width="160" height="100" fill="var(--bg-2)"/>
        <circle cx="80" cy="46" r="16" fill="var(--ink-dim)"/>
        <rect x="58" y="62" width="44" height="40" rx="4" fill="var(--ink-dim)"/>
        <rect x="0" y="85" width="160" height="15" fill="color-mix(in oklab, var(--ink) 8%, transparent)"/>
      </svg>
    );
  }
  if (type === "CLOSE") {
    return (
      <svg {...common} viewBox="0 0 160 100">
        <rect width="160" height="100" fill="var(--bg-2)"/>
        <circle cx="80" cy="56" r="36" fill="var(--ink-dim)"/>
        <circle cx="68" cy="52" r="3" fill="var(--bg-2)"/>
        <circle cx="92" cy="52" r="3" fill="var(--bg-2)"/>
        <path d="M66 68 Q80 74 94 68" stroke="var(--bg-2)" strokeWidth="2" fill="none" strokeLinecap="round"/>
      </svg>
    );
  }
  // INSERT
  return (
    <svg {...common} viewBox="0 0 160 100">
      <rect width="160" height="100" fill="var(--bg-2)"/>
      <rect x="36" y="20" width="88" height="60" rx="3" fill="var(--panel)" stroke="var(--line-2)"/>
      <rect x="44" y="28" width="72" height="6" fill="var(--ink-mute)" opacity="0.4"/>
      <rect x="44" y="40" width="60" height="4" fill="var(--ink-mute)" opacity="0.3"/>
      <rect x="44" y="48" width="64" height="4" fill="var(--ink-mute)" opacity="0.3"/>
      <rect x="44" y="56" width="44" height="4" fill="var(--ink-mute)" opacity="0.3"/>
    </svg>
  );
}

function Storyboard() {
  const [cells, setCells] = useState(INIT_CELLS);
  const [dragId, setDragId] = useState(null);
  const [overId, setOverId] = useState(null);
  const nextId = useRef(INIT_CELLS.length + 1);

  function updateCell(id, patch) {
    setCells((cs) => cs.map((c) => (c.id === id ? { ...c, ...patch } : c)));
  }
  function addCell() {
    const c = { id: nextId.current++, shot: "MED", text: "", dur: "0:03" };
    setCells((cs) => [...cs, c]);
  }
  function removeCell(id) {
    setCells((cs) => cs.filter((c) => c.id !== id));
  }
  function onDrop(targetId) {
    if (!dragId || dragId === targetId) return;
    setCells((cs) => {
      const a = cs.findIndex((c) => c.id === dragId);
      const b = cs.findIndex((c) => c.id === targetId);
      const n = cs.slice();
      const [moved] = n.splice(a, 1);
      n.splice(b, 0, moved);
      return n;
    });
    setDragId(null);
    setOverId(null);
  }
  function cycleShot(id, current) {
    const i = SHOT_TYPES.indexOf(current);
    updateCell(id, { shot: SHOT_TYPES[(i + 1) % SHOT_TYPES.length] });
  }

  const total = cells.reduce((acc, c) => {
    const [m, s] = c.dur.split(":").map((n) => parseInt(n || "0", 10));
    return acc + (m * 60 + s);
  }, 0);
  const totalStr = `${Math.floor(total / 60)}:${String(total % 60).padStart(2, "0")}`;

  return (
    <div className="sb-wrap">
      <div className="sb-toolbar">
        <button className="sb-btn primary" onClick={addCell}><window.Ic.plus /> Add shot</button>
        <button className="sb-btn" onClick={() => setCells(INIT_CELLS)}>Reset</button>
        <div style={{flex: 1}} />
        <div style={{fontFamily: "var(--mono)", fontSize: 12, color: "var(--ink-mute)", textTransform: "uppercase", letterSpacing: "0.08em"}}>
          {cells.length} shots · {totalStr} total
        </div>
      </div>

      <div className="sb-grid">
        {cells.map((c, idx) => (
          <div
            key={c.id}
            className={"sb-cell" + (dragId === c.id ? " dragging" : "") + (overId === c.id ? " over" : "")}
            draggable
            onDragStart={(e) => { setDragId(c.id); e.dataTransfer.effectAllowed = "move"; }}
            onDragOver={(e) => { e.preventDefault(); setOverId(c.id); }}
            onDragLeave={() => setOverId((o) => (o === c.id ? null : o))}
            onDrop={(e) => { e.preventDefault(); onDrop(c.id); }}
            onDragEnd={() => { setDragId(null); setOverId(null); }}
          >
            <div className="sb-cell-top">
              <span className="sb-shot-label" onClick={() => cycleShot(c.id, c.shot)} style={{cursor: "default"}}>{c.shot}</span>
              <span className="sb-num">#{String(idx + 1).padStart(2, "0")}</span>
              <ShotSketch type={c.shot} />
            </div>
            <div className="sb-cell-body">
              <textarea
                value={c.text}
                placeholder="Describe the shot or note dialogue…"
                onChange={(e) => updateCell(c.id, { text: e.target.value })}
                rows={3}
              />
              <div className="sb-cell-meta">
                <span>drag to reorder</span>
                <span style={{display: "flex", gap: 6, alignItems: "center"}}>
                  <input
                    className="sb-dur"
                    style={{width: 52, textAlign: "center", font: "inherit"}}
                    value={c.dur}
                    onChange={(e) => updateCell(c.id, { dur: e.target.value })}
                  />
                  <button
                    onClick={() => removeCell(c.id)}
                    style={{appearance: "none", border: "none", background: "transparent", color: "var(--ink-mute)", cursor: "default", padding: 2}}
                    aria-label="Remove"
                  ><window.Ic.x /></button>
                </span>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

window.Storyboard = Storyboard;
