/* eslint-disable */
const { useState, useEffect, useRef } = React;

async function api(path) {
  const r = await fetch(path);
  if (!r.ok) throw new Error(`${r.status}`);
  return r.json();
}

function Header() {
  return (
    <header className="site-hd">
      <div className="brand"><a href="/">Shiyaa</a></div>
      <div className="tagline">Tamil Fashion · AI Styled</div>
    </header>
  );
}

function Footer() {
  return (
    <footer className="footer">
      Shiyaa · {new Date().getFullYear()} · Affiliate links may earn commission
    </footer>
  );
}

function ProductRow({ product }) {
  // Both buttons go to the same Amazon affiliate URL — "CHECK PRICE" is a
  // gentler pre-purchase tap, "BUY" is the conversion CTA. Same destination.
  return (
    <div className="product">
      {product.image_url
        ? <img src={product.image_url} alt={product.name} loading="lazy" />
        : <div className="product-thumb-placeholder" />}
      <div className="info">
        <div className="name">{product.name}</div>
        {product.description && <div className="desc">{product.description}</div>}
      </div>
      <div className="actions">
        <a className="btn-check" href={product.affiliate_url} target="_blank" rel="noopener noreferrer sponsored">Check Price</a>
        <a className="btn-buy" href={product.affiliate_url} target="_blank" rel="noopener noreferrer sponsored">Buy</a>
      </div>
    </div>
  );
}

function ReelCard({ reel }) {
  const videoRef = useRef(null);
  const [playing, setPlaying] = useState(false);
  const isVideo = reel.kind === "reel" || (reel.video_url && /\.(mp4|mov|webm)(\?|$)/i.test(reel.video_url));
  const poster = reel.still_url;

  function togglePlay(e) {
    e.preventDefault();
    const v = videoRef.current;
    if (!v) return;
    if (v.paused) { v.play().catch(() => {}); setPlaying(true); }
    else { v.pause(); setPlaying(false); }
  }

  const products = reel.products || [];

  return (
    <article className="reel-card">
      <div className="reel-media" onClick={isVideo ? togglePlay : undefined}>
        {isVideo && reel.video_url ? (
          <>
            <video
              ref={videoRef}
              src={reel.video_url}
              poster={poster || undefined}
              playsInline
              muted={!playing}
              preload="metadata"
              loop
              onPlay={() => setPlaying(true)}
              onPause={() => setPlaying(false)}
            />
            {!playing && (
              <div className="play-badge" aria-hidden>
                <svg viewBox="0 0 48 48" width="38" height="38"><circle cx="24" cy="24" r="22" fill="rgba(0,0,0,0.55)" /><polygon points="19,15 35,24 19,33" fill="#fff" /></svg>
              </div>
            )}
          </>
        ) : (poster || reel.video_url) ? (
          <img src={poster || reel.video_url} alt={reel.idea || ""} loading="lazy" />
        ) : (
          <div className="no-media">no media</div>
        )}
        <div className="reel-meta-overlay">
          <span className="persona">@{reel.persona || "shiyaa"}</span>
          {reel.instagram_url && (
            <a className="ig-pill" href={reel.instagram_url} target="_blank" rel="noreferrer" onClick={(e) => e.stopPropagation()} aria-label="View on Instagram">IG ↗</a>
          )}
        </div>
      </div>

      <div className="reel-products">
        <div className="reel-caption">{(reel.idea || "Untitled reel").slice(0, 220)}</div>
        {products.length === 0
          ? <div className="reel-products-empty">Products coming soon</div>
          : (
            <div className="product-list">
              {products.map((p) => <ProductRow key={p.id} product={p} />)}
            </div>
          )}
      </div>
    </article>
  );
}

function HomeView() {
  const [reels, setReels] = useState(null);
  const [err, setErr] = useState(null);

  useEffect(() => {
    api("/api/reels?limit=60")
      .then((j) => setReels(j.data || []))
      .catch((e) => setErr(e.message));
  }, []);

  if (err) return <div className="empty">Couldn't load reels — try again later.</div>;
  if (reels == null) return <div className="empty">Loading…</div>;
  if (reels.length === 0) return <div className="empty">No reels published yet — check back soon.</div>;

  return <div className="reel-grid">{reels.map((r) => <ReelCard key={r.id} reel={r} />)}</div>;
}

function ReelDetailView({ slug, onBack }) {
  const [reel, setReel] = useState(null);
  const [err, setErr] = useState(null);

  useEffect(() => {
    setReel(null); setErr(null);
    api(`/api/reels/${encodeURIComponent(slug)}`)
      .then((j) => setReel(j.data))
      .catch((e) => setErr(e.status === 404 ? "Not found" : e.message));
  }, [slug]);

  if (err) return <div className="empty">{err === "Not found" ? "This reel isn't available." : `Couldn't load reel: ${err}`}</div>;
  if (!reel) return <div className="empty">Loading…</div>;

  return (
    <div>
      <a className="back" href="/" onClick={(e) => { e.preventDefault(); onBack(); }}>← All reels</a>
      <div className="reel-grid solo">
        <ReelCard reel={reel} />
      </div>
    </div>
  );
}

function App() {
  const [path, setPath] = useState(window.location.pathname);

  useEffect(() => {
    const onPop = () => setPath(window.location.pathname);
    window.addEventListener("popstate", onPop);
    return () => window.removeEventListener("popstate", onPop);
  }, []);

  function navigate(to) {
    if (to === path) return;
    window.history.pushState({}, "", to);
    setPath(to);
    window.scrollTo(0, 0);
  }

  const reelMatch = path.match(/^\/r\/([^/]+)\/?$/);

  return (
    <div className="shell">
      <Header />
      {reelMatch
        ? <ReelDetailView slug={decodeURIComponent(reelMatch[1])} onBack={() => navigate("/")} />
        : <HomeView />
      }
      <Footer />
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
