const { useState, useEffect, useMemo, useRef } = React;
let CATEGORIES, ANGLES, ADS, HERO_AD, TOP10, thumbSvg, pal, adsByCategory;

function fmtMoney(n) {
  if (!n) return "0";
  if (n >= 1000) return "$" + (n/1000).toFixed(n>=10000?0:1) + "k";
  return "$" + n;
}

function fmtDate(s) {
  if (!s) return null;
  const d = new Date(String(s).includes("T") ? s : s + "T00:00:00");
  if (isNaN(d.getTime())) return s;
  return d.toLocaleDateString("en-US", { year: "numeric", month: "short", day: "numeric" });
}

function fmtMonth(s) {
  if (!s) return null;
  const d = new Date(String(s).length === 7 ? s + "-01T00:00:00" : s);
  if (isNaN(d.getTime())) return s;
  return d.toLocaleDateString("en-US", { year: "numeric", month: "long" });
}

function daysRunning(launched) {
  if (!launched) return null;
  const d = new Date(String(launched).includes("T") ? launched : launched + "T00:00:00");
  if (isNaN(d.getTime())) return null;
  const days = Math.floor((Date.now() - d.getTime()) / 86400000);
  if (days < 0) return null;
  return days === 0 ? "today" : days === 1 ? "1 day" : `${days} days`;
}

function isStatic(ad) {
  return ad.mediaType === "static" || (!!ad.imageUrl && !ad.videoUrl);
}

function Thumb({ ad, idx }) {
  // Static image ad
  if (ad.imageUrl) {
    return (
      <div className="card-thumb">
        <img className="card-thumb-video" src={ad.imageUrl} alt={ad.title} />
      </div>
    );
  }
  // If we have a real video, show a still frame from it (seek ~1s in).
  if (ad.videoUrl) {
    return (
      <div className="card-thumb">
        <video
          className="card-thumb-video"
          src={ad.videoUrl + "#t=1"}
          muted
          playsInline
          preload="metadata"
          tabIndex={-1}
        />
      </div>
    );
  }
  const palette = pal((ad.id || idx) + (ad.title.length % 5));
  const html = thumbSvg(palette, ad.category, `${(ad.brand||'').toUpperCase()}`);
  return <div className="card-thumb" dangerouslySetInnerHTML={{__html: html}} />;
}

function Card({ ad, idx, onOpen }) {
  return (
    <div className="card" onClick={() => onOpen(ad)}>
      <Thumb ad={ad} idx={idx} />
      <span className={"card-type-badge" + (isStatic(ad) ? " static" : "")}>{isStatic(ad) ? "Static" : "Video"}</span>
      {ad.status && <span className="card-badge">{ad.status}</span>}
      {ad.fatigued && <span className="card-fatigue-badge">Fatigued</span>}
      {ad.duration && !isStatic(ad) && <span className="card-duration">{ad.duration}</span>}
      <div className="card-title">{ad.title}</div>
      <div className="card-overlay">
        <div className="play">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M8 5v14l11-7z"/></svg>
        </div>
        <div className="ov-title">{ad.title}</div>
        <div className="ov-meta">
          {ad.hookRate != null && <><span className="good">{ad.hookRate}% hook</span><span>·</span></>}
          {ad.ctr != null && <><span>{ad.ctr}% CTR</span><span>·</span></>}
          {ad.cpa != null && <span>${ad.cpa} CPS</span>}
        </div>
        <div className="ov-tags">
          {(ad.angles||[]).slice(0,3).map(t => <span key={t} className="ov-tag">{t}</span>)}
        </div>
      </div>
    </div>
  );
}

function Top10Card({ ad, rank, onOpen }) {
  return (
    <div className="card" onClick={() => onOpen(ad)}>
      <div className="top10-card">
        <div className="top10-rank">{rank}</div>
        <div className="top10-thumb">
          <Thumb ad={ad} idx={rank} />
          {ad.status && <span className="card-badge">{ad.status}</span>}
          {ad.duration && <span className="card-duration">{ad.duration}</span>}
          <div className="card-title">{ad.title}</div>
          <div className="card-overlay">
            <div className="play">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M8 5v14l11-7z"/></svg>
            </div>
            <div className="ov-title">{ad.title}</div>
            <div className="ov-meta">
              {ad.hookRate != null && <span className="good">{ad.hookRate}% hook</span>}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function Row({ title, subtitle, ads, onOpen, top10 }) {
  return (
    <section className={"row" + (top10 ? " row-top10" : "")}>
      <div className="row-header">
        <h2>{title}</h2>
        {subtitle && <span className="row-sub">{subtitle}</span>}
        <span className="see-all">Explore all <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="m9 6 6 6-6 6"/></svg></span>
      </div>
      <div className="row-scroll">
        {ads.map((ad, i) => top10
          ? <Top10Card key={ad.id} ad={ad} rank={i+1} onOpen={onOpen} />
          : <Card key={ad.id} ad={ad} idx={i} onOpen={onOpen} />
        )}
      </div>
    </section>
  );
}

function Hero({ ad, onOpen }) {
  if (!ad) {
    return (
      <section className="hero">
        <div className="hero-bg"></div>
        <div className="hero-placeholder-label">[ TOP PERFORMER WILL APPEAR HERE ]</div>
        <div className="hero-content">
          <div className="hero-eyebrow">Welcome to MAGICFLIX</div>
          <h1>Your swipe file starts empty.</h1>
          <p>Upload your first winning ad to begin building the library. Tag it by format, angle and hook style — every ad you add powers Browse, search and the brief generator.</p>
          <div className="hero-actions">
            <a href="Upload.html" className="btn btn-primary">
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M12 5v14M5 12h14"/></svg>
              Upload your first ad
            </a>
            <button className="btn btn-secondary">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4M12 8h.01"/></svg>
              How it works
            </button>
          </div>
        </div>
      </section>
    );
  }
  const heroVideo = useRef(null);
  useEffect(() => {
    const v = heroVideo.current;
    if (!v) return;
    const onTime = () => { if (v.currentTime >= 5) { v.currentTime = 0; v.play().catch(() => {}); } };
    v.addEventListener("timeupdate", onTime);
    v.play().catch(() => {});
    return () => v.removeEventListener("timeupdate", onTime);
  }, [ad && ad.videoUrl]);

  return (
    <section className="hero">
      <div className={"hero-bg" + (ad.videoUrl || ad.imageUrl ? " has-video" : "")}>
        {ad.videoUrl ? (
          <video
            ref={heroVideo}
            className="hero-video"
            src={ad.videoUrl}
            muted
            autoPlay
            playsInline
            preload="auto"
          />
        ) : ad.imageUrl ? (
          <img className="hero-video" src={ad.imageUrl} alt={ad.title} />
        ) : null}
      </div>
      {!ad.videoUrl && !ad.imageUrl && <div className="hero-placeholder-label">[ FEATURED VIDEO PLACEHOLDER · DROP MP4 HERE ]</div>}
      <div className="hero-content">
        <div className="hero-eyebrow">Top Performer · This Week</div>
        <h1>{ad.title}</h1>
        <p>"{ad.hookText}" — currently the highest-hooking ad in the swipe file.</p>
        <div className="hero-meta">
          <span className="pill"><span className="stat-num">{ad.brand}</span></span>
          {ad.hookRate != null && <><span className="pill">·</span><span className="pill"><span className="good">{ad.hookRate}% hook rate</span></span></>}
          {ad.cpa != null && <><span className="pill">·</span><span className="pill">${ad.cpa} CPS</span></>}
          {ad.spend != null && <><span className="pill">·</span><span className="pill"><span className="stat-num">{fmtMoney(ad.spend)}</span> spend</span></>}
        </div>
        <div className="hero-actions">
          <button className="btn btn-primary" onClick={() => onOpen(ad)}>
            <svg width="22" height="22" viewBox="0 0 24 24" fill="currentColor"><path d="M8 5v14l11-7z"/></svg>
            Play
          </button>
          <button className="btn btn-secondary" onClick={() => onOpen(ad)}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4M12 8h.01"/></svg>
            More info
          </button>
        </div>
      </div>
    </section>
  );
}

function ScriptBox({ script }) {
  const [copied, setCopied] = useState(false);
  const copy = () => {
    navigator.clipboard.writeText(script)
      .then(() => { setCopied(true); setTimeout(() => setCopied(false), 1500); })
      .catch(() => {});
  };
  return (
    <div className="script-box">
      <div className="script-box-head">
        <span className="label">Script</span>
        <button className="script-copy" onClick={copy}>
          {copied ? (
            <><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M5 12l5 5L20 7"/></svg>Copied</>
          ) : (
            <><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="9" y="9" width="11" height="11" rx="2"/><path d="M5 15V5a2 2 0 0 1 2-2h10"/></svg>Copy</>
          )}
        </button>
      </div>
      <pre className="script-text">{script}</pre>
    </div>
  );
}

function TranscriptBox({ transcript }) {
  const [copied, setCopied] = useState(false);
  const [expanded, setExpanded] = useState(false);
  const copy = () => {
    navigator.clipboard.writeText(transcript)
      .then(() => { setCopied(true); setTimeout(() => setCopied(false), 1500); })
      .catch(() => {});
  };
  const lines = transcript.split(/\r?\n/).filter(l => l.trim().length > 0);
  const preview = lines.slice(0, 3).join("\n");
  const hasMore = lines.length > 3 || transcript.length > 240;
  const shown = expanded || !hasMore ? transcript : preview;
  return (
    <div className="script-box">
      <div className="script-box-head">
        <span className="label">Transcript</span>
        <button className="script-copy" onClick={copy}>
          {copied ? (
            <><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M5 12l5 5L20 7"/></svg>Copied</>
          ) : (
            <><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="9" y="9" width="11" height="11" rx="2"/><path d="M5 15V5a2 2 0 0 1 2-2h10"/></svg>Copy</>
          )}
        </button>
      </div>
      <pre className="script-text">{shown}{!expanded && hasMore ? "…" : ""}</pre>
      {hasMore && (
        <button className="transcript-more" onClick={() => setExpanded(e => !e)}>
          {expanded ? "See less" : "See more"}
        </button>
      )}
    </div>
  );
}

function Modal({ ad, onClose, inList, onToggleList }) {
  if (!ad) return null;
  const palette = pal(ad.id || 0);
  const closeBtn = (
    <button className="modal-close" onClick={onClose}>
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M6 6l12 12M18 6 6 18"/></svg>
    </button>
  );
  const isComp = ad.source === "competitor";
  const info = (
    <>
      <div className="modal-title-row">
        <h2>{ad.title}</h2>
        <a className="btn btn-secondary modal-edit-btn" href={"Upload.html?edit=" + ad.id}>
          <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 20h9"/><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg>
          Edit
        </a>
      </div>
      <div className="modal-badge-row">
        <span className={"card-type-badge" + (isStatic(ad) ? " static" : "")} style={{position:"static"}}>{isStatic(ad) ? "Static" : "Video"}</span>
        {isComp && <span className="card-type-badge comp" style={{position:"static"}}>Competitor swipe</span>}
        {ad.fatigued && <span className="card-fatigue-badge" style={{position:"static"}}>Fatigued</span>}
      </div>
      {!isComp && <div className="modal-meta-row">
        {ad.hookRate != null && <><span className="good">{ad.hookRate}% hook</span><span>·</span></>}
        {ad.ctr != null && <><span><span className="num">{ad.ctr}%</span> CTR</span><span>·</span></>}
        {ad.cpl != null && <><span><span className="num">${ad.cpl}</span> CPSC</span><span>·</span></>}
        {ad.cpa != null && <><span><span className="num">${ad.cpa}</span> CPS</span><span>·</span></>}
        {ad.spend != null && <span>{fmtMoney(ad.spend)} spend</span>}
      </div>}
      {ad.hookText && <p className="desc"><b style={{color:"var(--text)"}}>Hook:</b> "{ad.hookText}"</p>}
      {ad.notes && <p className="desc">{ad.notes}</p>}
      <button className={"btn " + (inList ? "btn-primary" : "btn-secondary")} onClick={onToggleList} style={{marginTop:"4px", marginBottom:"4px"}}>
        {inList ? (
          <><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M5 12l5 5L20 7"/></svg>In My List</>
        ) : (
          <><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 5v14M5 12h14"/></svg>Add to My List</>
        )}
      </button>
      <div className="modal-side" style={{marginTop:"18px"}}>
        {ad.brand && <div style={{marginBottom:"14px"}}>
          <div className="label">Business</div>
          <div className="val">{ad.brand}</div>
        </div>}
        {ad.category && !isComp && <div style={{marginBottom:"14px"}}>
          <div className="label">Format</div>
          <div className="val">{ad.category}</div>
        </div>}
        {ad.launched && <div style={{marginBottom:"14px"}}>
          <div className="label">Launched</div>
          <div className="val">{fmtDate(ad.launched)}{daysRunning(ad.launched) && <span style={{color:"var(--text-3)"}}> · running {daysRunning(ad.launched)}</span>}</div>
        </div>}
        {ad.killed && <div style={{marginBottom:"14px"}}>
          <div className="label">Killed</div>
          <div className="val">{fmtDate(ad.killed)}</div>
        </div>}
        {ad.fatigued && <div style={{marginBottom:"14px"}}>
          <div className="label">Fatigue</div>
          <div className="val">
            {ad.fatigueMonth ? fmtMonth(ad.fatigueMonth) : "Fatigued"}
            {ad.fatigueSpend != null && <span style={{color:"var(--text-3)"}}> · {fmtMoney(ad.fatigueSpend)} spend before fatigue</span>}
          </div>
        </div>}
        {ad.metricsAsOf && !isComp && <div style={{marginBottom:"14px"}}>
          <div className="label">Metrics as of</div>
          <div className="val">{fmtDate(ad.metricsAsOf)}</div>
        </div>}
        {ad.added && <div style={{marginBottom:"14px"}}>
          <div className="label">Added</div>
          <div className="val">{fmtDate(ad.added)}</div>
        </div>}
        {ad.angles && ad.angles.length > 0 && <div>
          <div className="label">Angles</div>
          <div className="tag-row">
            {ad.angles.map(t => <span key={t} className="tag">{t}</span>)}
          </div>
        </div>}
      </div>
      {ad.script && <ScriptBox script={ad.script} />}
      {ad.transcript && <TranscriptBox transcript={ad.transcript} />}
    </>
  );
  return (
    <div className="modal-back open" onClick={(e) => { if (e.target.classList.contains('modal-back')) onClose(); }}>
      {ad.videoUrl ? (
        <div className="modal modal-portrait">
          {closeBtn}
          <div className="modal-portrait-video">
            <video src={ad.videoUrl} controls autoPlay playsInline />
          </div>
          <div className="modal-portrait-info">{info}</div>
        </div>
      ) : ad.imageUrl ? (
        <div className="modal modal-portrait">
          {closeBtn}
          <div className="modal-portrait-video">
            <img src={ad.imageUrl} alt={ad.title} style={{width:"100%",height:"100%",objectFit:"contain",background:"#000"}} />
          </div>
          <div className="modal-portrait-info">{info}</div>
        </div>
      ) : (
        <div className="modal">
          <div className="modal-hero" style={{background: `linear-gradient(135deg, ${palette[0]}, ${palette[1]} 60%, ${palette[0]})`}}>
            {closeBtn}
            <div style={{position:"absolute", top:"24px", right:"64px", fontFamily:"var(--mono)", fontSize:"11px", color:"rgba(255,255,255,.55)", letterSpacing:".08em"}}>
              [ NO VIDEO FILE{ad.duration ? ` · ${ad.duration}` : ''} ]
            </div>
            <div className="modal-play">
              <button className={"btn " + (inList ? "btn-primary" : "btn-secondary")} onClick={onToggleList}>
                {inList ? (
                  <><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M5 12l5 5L20 7"/></svg>In My list</>
                ) : (
                  <><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 5v14M5 12h14"/></svg>My list</>
                )}
              </button>
            </div>
          </div>
          <div className="modal-body">{info}</div>
        </div>
      )}
    </div>
  );
}

function EmptyLibrary() {
  return (
    <div className="empty">
      <h3>The library is empty.</h3>
      <p style={{marginBottom: "20px"}}>Once you upload ads they'll appear here, grouped by format with filters by angle and hook.</p>
      <a href="Upload.html" className="btn btn-primary" style={{display:"inline-flex"}}>
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M12 5v14M5 12h14"/></svg>
        Upload your first ad
      </a>
    </div>
  );
}

function App() {
  const [activeAngles, setActiveAngles] = useState([]);
  const [search, setSearch] = useState("");
  const [openAd, setOpenAd] = useState(null);
  const [view, setView] = useState("browse");
  const [formatFilter, setFormatFilter] = useState("all"); // all | video | static
  const [businessFilter, setBusinessFilter] = useState("");  // "" = all businesses
  const [myList, setMyList] = useState(() => {
    try { return JSON.parse(localStorage.getItem("mf_mylist") || "[]"); } catch { return []; }
  });

  function toggleList(id) {
    setMyList(prev => {
      const next = prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id];
      try { localStorage.setItem("mf_mylist", JSON.stringify(next)); } catch {}
      return next;
    });
  }

  useEffect(() => {
    const inp = document.getElementById('search-input');
    const handler = (e) => setSearch(e.target.value);
    inp.addEventListener('input', handler);
    return () => inp.removeEventListener('input', handler);
  }, []);

  // Wire the static nav links to switch views
  useEffect(() => {
    const links = Array.from(document.querySelectorAll('.nav-links a[data-view]'));
    const onClick = (e) => {
      e.preventDefault();
      const v = e.currentTarget.getAttribute('data-view');
      setView(v);
      setActiveAngles([]);
      setSearch("");
      setFormatFilter("all");
      setBusinessFilter("");
      const si = document.getElementById('search-input');
      if (si) si.value = "";
      links.forEach(l => l.classList.toggle('active', l === e.currentTarget));
      window.scrollTo({ top: 0, behavior: 'smooth' });
    };
    links.forEach(l => l.addEventListener('click', onClick));
    return () => links.forEach(l => l.removeEventListener('click', onClick));
  }, []);

  const ownAds = useMemo(() => ADS.filter(a => a.source !== "competitor"), []);
  const competitorAds = useMemo(() => ADS.filter(a => a.source === "competitor"), []);

  const isFiltering = activeAngles.length > 0 || search.trim().length > 0 || formatFilter !== "all" || !!businessFilter;
  const isEmpty = ADS.length === 0;

  const filteredAds = useMemo(() => {
    const q = search.trim().toLowerCase();
    return ownAds.filter(a => {
      const angleOk = activeAngles.length === 0 || activeAngles.every(t => (a.angles||[]).includes(t));
      const formatOk = formatFilter === "all" || (formatFilter === "static" ? isStatic(a) : !isStatic(a));
      const bizOk = !businessFilter || a.brand === businessFilter;
      const searchOk = !q || (
        (a.title||'').toLowerCase().includes(q) ||
        (a.brand||'').toLowerCase().includes(q) ||
        (a.category||'').toLowerCase().includes(q) ||
        (a.hookText||'').toLowerCase().includes(q) ||
        (a.angles||[]).some(an => an.toLowerCase().includes(q))
      );
      return angleOk && formatOk && bizOk && searchOk;
    });
  }, [activeAngles, search, formatFilter, businessFilter, ownAds]);

  function toggleAngle(t) {
    setActiveAngles(prev => prev.includes(t) ? prev.filter(x => x!==t) : [...prev, t]);
  }

  const topPerformers = useMemo(() => [...ownAds].sort((a, b) => (b.hookRate || 0) - (a.hookRate || 0)), [ownAds]);
  const recentAds = useMemo(() => [...ownAds].sort((a, b) => new Date(b.added || b.createdAt || 0) - new Date(a.added || a.createdAt || 0)), [ownAds]);
  const businesses = useMemo(() => [...new Set(ownAds.map(a => a.brand).filter(Boolean))].sort(), [ownAds]);
  const myListAds = ADS.filter(a => myList.includes(a.id));

  return (
    <>
      <Hero ad={HERO_AD} onOpen={setOpenAd} />

      {!isEmpty && view === "browse" && (
        <div className="filter-stack">
          <div className="filter-bar">
            <span className="filter-label">Format</span>
            {[["all","All"],["video","Video"],["static","Static"]].map(([v,lbl]) => (
              <button key={v} className={"chip" + (formatFilter === v ? " active" : "")} onClick={() => setFormatFilter(v)}>{lbl}</button>
            ))}
            <span className="filter-label" style={{marginLeft:"16px"}}>Business</span>
            <select className="filter-select" value={businessFilter} onChange={(e) => setBusinessFilter(e.target.value)}>
              <option value="">All businesses</option>
              {businesses.map(b => <option key={b} value={b}>{b}</option>)}
            </select>
          </div>
          <div className="filter-bar">
            <span className="filter-label">Angle</span>
            {ANGLES.map(t => (
              <button key={t} className={"chip" + (activeAngles.includes(t) ? " active" : "")} onClick={() => toggleAngle(t)}>
                {t}
              </button>
            ))}
            {isFiltering && (
              <button className="chip" style={{color:"var(--accent)", borderColor:"transparent"}} onClick={() => { setActiveAngles([]); setFormatFilter("all"); setBusinessFilter(""); }}>
                Clear all
              </button>
            )}
          </div>
        </div>
      )}

      <div className="rows">
        {isEmpty ? (
          <EmptyLibrary />
        ) : view === "browse" && isFiltering ? (
          filteredAds.length === 0 ? (
            <div className="empty">
              <h3>No ads match this combination</h3>
              <p>Try removing a filter or broadening your search.</p>
            </div>
          ) : (
            <Row
              title={search.trim() ? `Results for "${search.trim()}"` : "Filtered ads"}
              subtitle={`${filteredAds.length} found`}
              ads={filteredAds}
              onOpen={setOpenAd}
            />
          )
        ) : view === "top" ? (
          <Row title="Top Performers" subtitle="Ranked by hook rate" ads={topPerformers} onOpen={setOpenAd} top10 />
        ) : view === "recent" ? (
          <Row title="Recently Added" subtitle={`${recentAds.length} ads`} ads={recentAds} onOpen={setOpenAd} />
        ) : view === "competitor" ? (
          competitorAds.length === 0 ? (
            <div className="empty">
              <h3>No competitor swipes yet</h3>
              <p>When uploading, choose "Competitor swipe" to save ads from other brands here.</p>
            </div>
          ) : (
            <Row title="Competitor Swipes" subtitle={`${competitorAds.length} saved`} ads={competitorAds} onOpen={setOpenAd} />
          )
        ) : view === "business" ? (
          <>
            <div className="filter-bar" style={{marginBottom:"8px"}}>
              <span className="filter-label">Show</span>
              <select className="filter-select" value={businessFilter} onChange={(e) => setBusinessFilter(e.target.value)}>
                <option value="">All businesses</option>
                {businesses.map(b => <option key={b} value={b}>{b}</option>)}
              </select>
            </div>
            {businesses.filter(b => !businessFilter || b === businessFilter).map(b => {
              const ads = ownAds.filter(a => a.brand === b);
              return <Row key={b} title={b} subtitle={`${ads.length} ad${ads.length===1?'':'s'}`} ads={ads} onOpen={setOpenAd} />;
            })}
          </>
        ) : view === "mylist" ? (
          myListAds.length === 0 ? (
            <div className="empty">
              <h3>Your list is empty</h3>
              <p>Open any ad and tap "Add to My List" to save it here.</p>
            </div>
          ) : (
            <Row title="My List" subtitle={`${myListAds.length} saved`} ads={myListAds} onOpen={setOpenAd} />
          )
        ) : (
          <>
            {TOP10.length >= 5 && <Row title="Top 10 ads this week" subtitle="Ranked by lowest CPSC" ads={TOP10} onOpen={setOpenAd} top10 />}
            {CATEGORIES.map(cat => {
              const ads = adsByCategory(cat);
              if (ads.length === 0) return null;
              return <Row key={cat} title={cat} subtitle={`${ads.length} in library`} ads={ads} onOpen={setOpenAd} />;
            })}
          </>
        )}
      </div>

      {openAd && <Modal ad={openAd} onClose={() => setOpenAd(null)} inList={myList.includes(openAd.id)} onToggleList={() => toggleList(openAd.id)} />}
    </>
  );
}

window.SR_READY.then(() => {
  ({ CATEGORIES, ANGLES, ADS, HERO_AD, TOP10, thumbSvg, pal, adsByCategory } = window.SR);
  ReactDOM.createRoot(document.getElementById('root')).render(<App />);
});
