// TEMPLATES gallery. Admins (see supabase/migrations/20260903000006_admins.sql)
// also get a "New template" button and, on hover, edit/delete controls on
// each card — see CreateTemplatePopover below and onEditTemplate's wiring
// in app.jsx (opens ProjectEditor in `mode="template"`, writing to the
// "templates" table instead of "projects").
function TemplatesPage({ onOpenTemplate, isAdmin, onEditTemplate }) {
  const [filter, setFilter] = useState("all");
  const templates = useTemplates();
  const [refreshKey, setRefreshKey] = useState(0);
  const [creating, setCreating] = useState(false);
  const [busyId, setBusyId] = useState(null);

  // useTemplates() only fetches once — force a fresh list after a
  // create/delete by refetching directly instead.
  const [list, setList] = useState(templates);
  useEffect(() => { setList(templates); }, [templates]);
  useEffect(() => {
    if (refreshKey === 0) return;
    let alive = true;
    API.listTemplates().then((t) => { if (alive) setList(t); });
    return () => { alive = false; };
  }, [refreshKey]);

  const handleDelete = async (t) => {
    if (!window.confirm(`Delete "${t.name}"? This can't be undone.`)) return;
    setBusyId(t.id);
    try {
      await API.deleteTemplate(t.id);
      setRefreshKey((k) => k + 1);
    } catch (e) {
      window.alert(`Delete failed: ${e.message}`);
    } finally {
      setBusyId(null);
    }
  };

  const filters = [
    { id: "all", label: "All" },
    { id: "LinkedIn", label: "LinkedIn" },
    { id: "Spotify", label: "Spotify" },
    { id: "Instagram", label: "Instagram" },
    { id: "YouTube", label: "YouTube" },
  ];

  if (!list) {
    return (
      <div className="fade-in">
        <div className="eyebrow">TEMPLATES</div>
        <h1 className="page-title">Four formats,<br />every episode.</h1>
        <div className="grid-3" style={{ marginTop: 48 }}>
          {[0, 1, 2].map((i) => (
            <div key={i} className="skeleton-bar" style={{ height: 280, borderRadius: 14 }}></div>
          ))}
        </div>
      </div>
    );
  }

  const filtered = filter === "all" ? list : list.filter((t) => t.platform === filter);

  return (
    <div className="fade-in">
      <div className="eyebrow">TEMPLATES</div>
      <h1 className="page-title">
        Four formats,<br />
        every episode.
      </h1>
      <p className="page-subtitle">
        A LinkedIn carousel plus podcast covers for Spotify, Instagram, and YouTube. Drop in the episode title and guest — on-brand by default, fully editable.
      </p>

      {/* FILTERS */}
      <div style={{ marginTop: 32, display: "flex", gap: 6, flexWrap: "wrap", justifyContent: "space-between", alignItems: "center" }}>
        <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
          {filters.map((f) => (
            <button
              key={f.id}
              className="pill"
              style={{
                padding: "8px 14px",
                fontSize: 13,
                background: filter === f.id ? "var(--ink)" : "var(--surface-2)",
                color: filter === f.id ? "var(--surface)" : "var(--ink-2)",
                borderColor: filter === f.id ? "var(--ink)" : "var(--line)",
                cursor: "pointer",
              }}
              onClick={() => setFilter(f.id)}
            >
              {f.label}
            </button>
          ))}
        </div>
        {isAdmin && (
          <div style={{ position: "relative", flexShrink: 0 }}>
            <button className="btn btn-surface" onClick={() => setCreating((c) => !c)}>
              <Icons.Plus size={16} /> New template
            </button>
            {creating && (
              <CreateTemplatePopover
                onClose={() => setCreating(false)}
                onCreated={(t) => { setCreating(false); setRefreshKey((k) => k + 1); onEditTemplate(t); }}
              />
            )}
          </div>
        )}
      </div>

      {/* GRID */}
      <div className="grid-3" style={{ marginTop: 28 }}>
        {filtered.map((t) => (
          <div key={t.id} className="card hover-card" style={{ padding: 14, position: "relative" }} onClick={() => onOpenTemplate(t)}>
            {isAdmin && (
              <div className="template-card-actions" onClick={(e) => e.stopPropagation()}>
                <button
                  className="btn btn-sm btn-surface"
                  style={{ padding: "5px 8px" }}
                  onClick={() => onEditTemplate(t)}
                  title="Edit template"
                >
                  <Icons.Edit size={14} />
                </button>
                <button
                  className="btn btn-sm btn-surface"
                  style={{ padding: "5px 8px" }}
                  onClick={() => handleDelete(t)}
                  disabled={busyId === t.id}
                  title="Delete template"
                >
                  {busyId === t.id ? <span className="spinner" style={{ width: 12, height: 12 }} /> : <Icons.Trash size={14} />}
                </button>
              </div>
            )}
            <TemplateThumbnail template={t} />
            <div style={{ padding: "14px 6px 4px" }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 12 }}>
                <div style={{ flex: 1 }}>
                  <div style={{ fontFamily: "var(--font-display)", fontSize: 18, fontWeight: 600, letterSpacing: "-0.015em" }}>{t.name}</div>
                  <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 4 }}>{t.platform}</div>
                </div>
                <PlatformBadge platform={t.platform} />
              </div>
              <p style={{ fontSize: 12.5, color: "var(--ink-3)", marginTop: 12, lineHeight: 1.45 }}>{t.description}</p>
              <div style={{ marginTop: 14, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                <div style={{ display: "flex", gap: 6 }}>
                  <span className="pill" style={{ fontSize: 11 }}>{t.width}×{t.height}</span>
                  <span className="pill" style={{ fontSize: 11 }}>{t.slides.length} slide{t.slides.length === 1 ? "" : "s"}</span>
                </div>
                <Icons.ArrowRight size={14} />
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// Anchored popover (opened from the "New template" button) that creates a
// bare template row, then hands it off so the caller can drop straight
// into the editor to design it.
function CreateTemplatePopover({ onClose, onCreated }) {
  const [name, setName] = useState("");
  const [platform, setPlatform] = useState("LinkedIn");
  const [width, setWidth] = useState(1080);
  const [height, setHeight] = useState(1080);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState("");

  const submit = async (e) => {
    e.preventDefault();
    if (busy) return;
    setBusy(true);
    setError("");
    try {
      const { template } = await API.createTemplate({
        name: name.trim() || "Untitled template",
        platform,
        width: Number(width) || 1080,
        height: Number(height) || 1080,
        slides: [{ background: "#FFFFFF", elements: [] }],
      });
      onCreated(template);
    } catch (e) {
      setError(e.message || "Couldn't create the template.");
      setBusy(false);
    }
  };

  return (
    <>
      <div style={{ position: "fixed", inset: 0, zIndex: 40 }} onClick={onClose} />
      <form
        onSubmit={submit}
        className="fade-in"
        style={{
          position: "absolute", top: "calc(100% + 8px)", right: 0, zIndex: 41,
          width: 320, background: "var(--surface-2)", border: "1px solid var(--line)",
          borderRadius: 12, padding: 16, boxShadow: "0 12px 32px rgba(0,0,0,0.3)",
          textAlign: "left",
        }}
        onClick={(e) => e.stopPropagation()}
      >
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          <div>
            <label style={{ fontSize: 12, color: "var(--ink-3)", display: "block", marginBottom: 6 }}>Name</label>
            <input className="input" value={name} onChange={(e) => setName(e.target.value)} placeholder="Untitled template" autoFocus />
          </div>
          <div>
            <label style={{ fontSize: 12, color: "var(--ink-3)", display: "block", marginBottom: 6 }}>Platform</label>
            <select className="input" value={platform} onChange={(e) => setPlatform(e.target.value)}>
              <option>LinkedIn</option>
              <option>Spotify</option>
              <option>Instagram</option>
              <option>YouTube</option>
            </select>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
            <div>
              <label style={{ fontSize: 12, color: "var(--ink-3)", display: "block", marginBottom: 6 }}>Width</label>
              <input className="input" type="number" value={width} onChange={(e) => setWidth(e.target.value)} min={1} />
            </div>
            <div>
              <label style={{ fontSize: 12, color: "var(--ink-3)", display: "block", marginBottom: 6 }}>Height</label>
              <input className="input" type="number" value={height} onChange={(e) => setHeight(e.target.value)} min={1} />
            </div>
          </div>
          {error && <div style={{ color: "var(--ink)", fontSize: 13 }}>{error}</div>}
          <div style={{ display: "flex", gap: 8 }}>
            <button type="submit" className="btn btn-primary btn-sm" disabled={busy} style={{ flex: 1, justifyContent: "center" }}>
              {busy ? <span className="spinner" /> : <Icons.Plus size={14} />} Create
            </button>
            <button type="button" className="btn btn-ghost btn-sm" onClick={onClose} disabled={busy}>Cancel</button>
          </div>
        </div>
      </form>
    </>
  );
}

function PlatformBadge({ platform }) {
  const map = {
    Instagram: { Icon: Icons.Instagram, color: "#070707" },
    LinkedIn: { Icon: Icons.Linkedin, color: "#070707" },
    Spotify: { Icon: Icons.Spotify, color: "#070707" },
    YouTube: { Icon: Icons.Youtube, color: "#070707" },
  };
  const v = map[platform];
  if (!v) return null;
  const { Icon, color } = v;
  return (
    <div style={{ width: 32, height: 32, borderRadius: 8, background: color, display: "grid", placeItems: "center", color: "white", flex: "0 0 auto" }}>
      <Icon size={16} />
    </div>
  );
}

window.TemplatesPage = TemplatesPage;
