// Public video page — /#/v/<slug>
//
// Renders a published video_drafts row as a shareable URL. Built so the
// admin Video Studio can hand the user a link they can paste into a
// LinkedIn post — LinkedIn unfurls the OG meta and shows a card linking
// back to the page.
//
// Anon-readable via /api/video?slug=...; the API gates on is_published.

const { useState: useStateV, useEffect: useEffectV } = React;

function VideoPage({ slug, onNav }) {
  const [data, setData] = useStateV(null);
  const [error, setError] = useStateV(null);
  const [copied, setCopied] = useStateV(false);

  useEffectV(() => {
    if (!slug) return;
    let alive = true;
    fetch(`/api/video?slug=${encodeURIComponent(slug)}`)
      .then((r) => r.ok ? r.json() : r.json().then((j) => Promise.reject(j)))
      .then((d) => { if (alive) setData(d.video); })
      .catch((e) => { if (alive) setError(e?.error || "Video not found"); });
    return () => { alive = false; };
  }, [slug]);

  function copyLink() {
    const url = window.location.href;
    if (navigator.clipboard) {
      navigator.clipboard.writeText(url).then(() => {
        setCopied(true);
        setTimeout(() => setCopied(false), 1800);
      }, () => {});
    }
  }

  // Loading state — keep it minimal so the dark page chrome doesn't flash.
  if (!data && !error) {
    return (
      <div style={pageStyle}>
        <div style={{ ...containerStyle, color: "rgba(255,255,255,0.5)", textAlign: "center", padding: 80 }}>
          Loading…
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div style={pageStyle}>
        <div style={containerStyle}>
          <div style={breadcrumb}>
            <a href="#" onClick={(e) => { e.preventDefault(); onNav && onNav("home"); }} style={breadcrumbLink}>← Shipping Clarity</a>
            <span style={breadcrumbSep}> / </span>
            <span>Video not found</span>
          </div>
          <div style={{ marginTop: 80, textAlign: "center" }}>
            <div style={{ fontSize: 56, marginBottom: 16, opacity: 0.4 }}>📹</div>
            <h1 style={{ fontSize: 28, margin: "0 0 12px", color: "#fff", fontWeight: 700 }}>Video not found</h1>
            <p style={{ fontSize: 15, color: "rgba(255,255,255,0.55)", maxWidth: 460, margin: "0 auto 28px", lineHeight: 1.6 }}>
              This video may have been unpublished or the link could be wrong.
              Head back to the homepage to see what's live.
            </p>
            <button onClick={() => onNav && onNav("home")}
                    style={{ padding: "12px 24px", fontSize: 15, fontWeight: 600,
                             background: "#5fa9ff", color: "#0a1224", border: "none", borderRadius: 6, cursor: "pointer" }}>
              Back to Shipping Clarity →
            </button>
          </div>
        </div>
      </div>
    );
  }

  const stamp = data.published_at
    ? new Date(data.published_at).toLocaleDateString("en-US", { year: "numeric", month: "short", day: "numeric" })
    : null;
  const minutes = data.duration_seconds ? Math.round(data.duration_seconds / 60) : null;

  return (
    <div style={pageStyle}>
      <div style={containerStyle}>
        <div style={breadcrumb}>
          <a href="#" onClick={(e) => { e.preventDefault(); onNav && onNav("home"); }} style={breadcrumbLink}>← Shipping Clarity</a>
          <span style={breadcrumbSep}> / </span>
          <span>Video</span>
        </div>

        <div style={eyebrow}>
          <span style={eyebrowDot} />
          REPORT · VIDEO {minutes ? `· ${minutes} MIN` : ""} {stamp ? `· ${stamp.toUpperCase()}` : ""}
        </div>

        <h1 style={titleStyle}>{data.title || "Untitled video"}</h1>

        {data.description && (
          <p style={descStyle}>{data.description}</p>
        )}

        {/* The video player. data.format is "16x9" / "9x16" / "1x1"; the
            container's aspect-ratio CSS handles the responsive box. */}
        <div style={{
          ...playerWrap,
          aspectRatio: data.format === "9x16" ? "9 / 16"
                       : data.format === "1x1" ? "1 / 1"
                       : "16 / 9",
          maxWidth: data.format === "9x16" ? 480 : 1100,
        }}>
          {data.embed_url ? (
            <iframe
              src={data.embed_url}
              title={data.title || "Video"}
              allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
              allowFullScreen
              style={{ width: "100%", height: "100%", display: "block", border: 0, borderRadius: 8 }}
            />
          ) : (
            // preload="none" — don't fetch any MP4 bytes until the visitor
            // clicks play. Cuts Supabase Storage egress massively on
            // link-preview crawls + page visits that don't end in play.
            <video
              src={data.video_public_url}
              controls
              playsInline
              preload="none"
              poster={data.poster_url || undefined}
              style={{ width: "100%", height: "100%", display: "block", borderRadius: 8 }}
            />
          )}
        </div>

        <div style={shareRow}>
          <button onClick={copyLink} style={copyBtn}>
            {copied ? "✓ Link copied" : "Copy link"}
          </button>
          <a
            href={`https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(window.location.href)}`}
            target="_blank" rel="noopener noreferrer"
            style={linkedinBtn}
          >
            Share on LinkedIn →
          </a>
          {data.video_public_url && !data.embed_url && (
            <a href={data.video_public_url} download style={downloadLink}>
              ⬇ Download MP4
            </a>
          )}
        </div>

        <div style={footStyle}>
          Independent freight intelligence · public-record sourced · shippingclarity.com
        </div>
      </div>
    </div>
  );
}

const pageStyle = {
  background: "radial-gradient(circle at 30% 0%, #1d2d52 0%, #0a1224 55%, #050913 100%)",
  color: "#fff",
  minHeight: "100vh",
  fontFamily: '"Helvetica Neue", Helvetica, Arial, sans-serif',
};

const containerStyle = {
  maxWidth: 1180,
  margin: "0 auto",
  padding: "32px 24px 96px",
};

const breadcrumb = {
  fontSize: 13,
  color: "rgba(255,255,255,0.55)",
  marginBottom: 28,
  letterSpacing: "0.01em",
};

const breadcrumbLink = { color: "#5fa9ff", textDecoration: "none" };
const breadcrumbSep  = { opacity: 0.45, margin: "0 4px" };

const eyebrow = {
  display: "inline-flex", alignItems: "center", gap: 8,
  fontFamily: "'Helvetica Neue', Helvetica, Arial, sans-serif",
  fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase",
  color: "#5fa9ff", fontWeight: 700, marginBottom: 14,
};

const eyebrowDot = {
  display: "inline-block", width: 8, height: 8, borderRadius: "50%",
  background: "#5fa9ff",
};

const titleStyle = {
  fontFamily: "Georgia, 'Times New Roman', serif",
  fontSize: "clamp(32px, 5vw, 52px)",
  lineHeight: 1.1,
  letterSpacing: "-0.02em",
  fontWeight: 700,
  margin: "0 0 18px",
  color: "#fff",
  maxWidth: 940,
};

const descStyle = {
  fontSize: 18,
  lineHeight: 1.55,
  color: "rgba(255,255,255,0.78)",
  maxWidth: 820,
  margin: "0 0 28px",
};

const playerWrap = {
  width: "100%",
  background: "#000",
  borderRadius: 8,
  border: "1px solid rgba(255,255,255,0.10)",
  overflow: "hidden",
  marginBottom: 24,
  boxShadow: "0 16px 48px rgba(0,0,0,0.55)",
};

const shareRow = {
  display: "flex",
  flexWrap: "wrap",
  gap: 12,
  marginBottom: 40,
};

const copyBtn = {
  padding: "10px 18px",
  fontSize: 14,
  fontWeight: 600,
  background: "#5fa9ff",
  color: "#0a1224",
  border: "none",
  borderRadius: 6,
  cursor: "pointer",
  fontFamily: "inherit",
};

const linkedinBtn = {
  padding: "10px 18px",
  fontSize: 14,
  fontWeight: 600,
  background: "transparent",
  color: "#fff",
  border: "1px solid rgba(255,255,255,0.28)",
  borderRadius: 6,
  textDecoration: "none",
  display: "inline-flex",
  alignItems: "center",
};

const downloadLink = {
  padding: "10px 18px",
  fontSize: 14,
  color: "rgba(255,255,255,0.65)",
  textDecoration: "none",
  display: "inline-flex",
  alignItems: "center",
};

const footStyle = {
  paddingTop: 28,
  borderTop: "1px solid rgba(255,255,255,0.10)",
  fontSize: 12,
  color: "rgba(255,255,255,0.45)",
  letterSpacing: "0.04em",
};

window.VideoPage = VideoPage;


// ============================================================
// Public video gallery — /#/videos
// Index of every published video. Backed by /api/video?list=all
// (server-side filter on is_published=true). Cards link to the
// individual /#/v/<slug> pages, which already exist.
// ============================================================

function VideoGalleryPage({ onNav }) {
  const [videos, setVideos] = useStateV([]);
  const [loading, setLoading] = useStateV(true);
  const [error, setError] = useStateV(null);
  const [filter, setFilter] = useStateV("all"); // "all" or "featured"

  useEffectV(() => {
    let alive = true;
    setLoading(true);
    setError(null);
    fetch(`/api/video?list=${filter}&limit=12`)
      .then((r) => r.ok ? r.json() : r.json().then((j) => Promise.reject(j)))
      .then((d) => { if (alive) { setVideos(d.videos || []); setLoading(false); } })
      .catch((e) => { if (alive) { setError(e?.error || "Could not load videos"); setLoading(false); } });
    return () => { alive = false; };
  }, [filter]);

  function fmtDuration(secs) {
    if (!secs && secs !== 0) return null;
    const m = Math.floor(secs / 60);
    const s = Math.round(secs % 60);
    return `${m}:${String(s).padStart(2, "0")}`;
  }

  function fmtDate(iso) {
    if (!iso) return "";
    try {
      return new Date(iso).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" });
    } catch { return ""; }
  }

  return (
    <div className="vg-page">
      <style>{`
        .vg-page {
          background: #0a1224; min-height: 100vh; color: #fff;
          padding: 80px 24px 120px;
        }
        .vg-inner { max-width: 1280px; margin: 0 auto; }
        .vg-eyebrow {
          font-family: var(--font-mono); font-size: 11px; letter-spacing: 0.32em;
          text-transform: uppercase; color: rgba(255,255,255,0.55);
          margin-bottom: 14px;
        }
        .vg-title {
          font-family: var(--font-serif); font-size: 48px; line-height: 1.05;
          margin: 0 0 12px; font-weight: 700;
        }
        .vg-title em { color: #5fa9ff; font-style: italic; }
        .vg-dek {
          font-size: 17px; line-height: 1.55; color: rgba(255,255,255,0.72);
          max-width: 720px; margin: 0 0 28px;
        }
        .vg-filters {
          display: flex; gap: 6px; margin-bottom: 36px;
          padding-bottom: 18px;
          border-bottom: 1px solid rgba(255,255,255,0.12);
        }
        .vg-filter {
          font-family: var(--font-mono); font-size: 11px; letter-spacing: 0.16em;
          text-transform: uppercase; color: rgba(255,255,255,0.62);
          background: transparent;
          border: 1px solid rgba(255,255,255,0.18);
          padding: 7px 14px; border-radius: 999px;
          cursor: pointer; transition: all 120ms;
        }
        .vg-filter:hover { color: #fff; border-color: rgba(255,255,255,0.42); }
        .vg-filter.is-on {
          background: #5fa9ff; color: #0a1224; border-color: #5fa9ff;
        }
        .vg-grid {
          display: grid; gap: 28px;
          grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
        }
        .vg-card {
          display: flex; flex-direction: column;
          background: #050913; border: 1px solid rgba(255,255,255,0.08);
          border-radius: 10px; overflow: hidden;
          color: #fff; text-decoration: none;
          transition: transform 200ms, border-color 200ms, box-shadow 200ms;
        }
        .vg-card:hover {
          transform: translateY(-3px);
          border-color: rgba(95,169,255,0.45);
          box-shadow: 0 18px 32px rgba(0,0,0,0.32);
        }
        .vg-card-poster {
          aspect-ratio: 16 / 9; background: #1d2d52;
          background-size: cover; background-position: center;
          position: relative;
        }
        .vg-card-play {
          position: absolute; inset: 0;
          display: flex; align-items: center; justify-content: center;
          background: linear-gradient(180deg, rgba(0,0,0,0) 50%, rgba(0,0,0,0.55) 100%);
        }
        .vg-card-play svg { filter: drop-shadow(0 4px 8px rgba(0,0,0,0.5)); }
        .vg-card-dur {
          position: absolute; bottom: 10px; right: 10px;
          background: rgba(0,0,0,0.78); color: #fff;
          font-family: var(--font-mono); font-size: 11px;
          padding: 3px 8px; border-radius: 4px;
        }
        .vg-card-body { padding: 18px 20px 22px; flex: 1; display: flex; flex-direction: column; }
        .vg-card-title {
          font-family: var(--font-serif); font-size: 20px; line-height: 1.3;
          margin: 0 0 8px; font-weight: 700;
        }
        .vg-card-desc {
          font-size: 13px; line-height: 1.55; color: rgba(255,255,255,0.65);
          margin: 0 0 14px;
          display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical;
          overflow: hidden;
        }
        .vg-card-meta {
          font-family: var(--font-mono); font-size: 10px; letter-spacing: 0.12em;
          text-transform: uppercase; color: rgba(255,255,255,0.45);
          margin-top: auto; padding-top: 12px;
          border-top: 1px solid rgba(255,255,255,0.08);
        }
        .vg-empty {
          padding: 80px 0; text-align: center;
          color: rgba(255,255,255,0.55); font-size: 15px;
        }
      `}</style>

      <div className="vg-inner">
        <div className="vg-eyebrow">Video library</div>
        <h1 className="vg-title">The freight market, <em>on screen</em>.</h1>
        <p className="vg-dek">
          Every video we publish — distress flags, dossier deep-dives, market
          reads — in one place. Built with our own data engine, narrated, and
          ready to share.
        </p>

        <div className="vg-filters">
          <button
            className={"vg-filter" + (filter === "all" ? " is-on" : "")}
            onClick={() => setFilter("all")}
          >
            All videos
          </button>
          <button
            className={"vg-filter" + (filter === "featured" ? " is-on" : "")}
            onClick={() => setFilter("featured")}
          >
            Featured
          </button>
        </div>

        {loading && <div className="vg-empty">Loading the library…</div>}
        {error && <div className="vg-empty" style={{ color: "#ff7a7a" }}>{error}</div>}
        {!loading && !error && videos.length === 0 && (
          <div className="vg-empty">
            No videos published yet. Check back soon — we publish a new dossier most weeks.
          </div>
        )}
        {!loading && !error && videos.length > 0 && (
          <div className="vg-grid">
            {videos.map((v) => (
              <a
                key={v.slug}
                href={`#/v/${v.slug}`}
                className="vg-card"
                onClick={(e) => {
                  e.preventDefault();
                  window.location.hash = `#/v/${v.slug}`;
                }}
              >
                <div
                  className="vg-card-poster"
                  style={v.poster_url ? { backgroundImage: `url(${v.poster_url})` } : null}
                >
                  <div className="vg-card-play">
                    <svg width="56" height="56" viewBox="0 0 56 56" aria-hidden="true">
                      <circle cx="28" cy="28" r="27" fill="rgba(255,255,255,0.92)" />
                      <polygon points="22,18 22,38 38,28" fill="#0a1224" />
                    </svg>
                  </div>
                  {fmtDuration(v.duration_seconds) && (
                    <div className="vg-card-dur">{fmtDuration(v.duration_seconds)}</div>
                  )}
                </div>
                <div className="vg-card-body">
                  <h3 className="vg-card-title">{v.title}</h3>
                  {v.description && (
                    <p className="vg-card-desc">{v.description}</p>
                  )}
                  <div className="vg-card-meta">
                    {fmtDate(v.published_at) || "Published"}
                    {v.format ? ` · ${v.format}` : ""}
                  </div>
                </div>
              </a>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

window.VideoGalleryPage = VideoGalleryPage;
