/* CLAY KIT - provider app-tiles, avatars, shared table cells and the
   scroll hooks the 3 versions share. Exposes onto window.CK. */
const { useState, useEffect, useRef, useLayoutEffect } = React;

/* ---------- provider app icons (monochrome Clay-style glyphs) ---------- */
function ProvGlyph({ ic }) {
  const s = { width: 13, height: 13, fill: "none", stroke: "currentColor", strokeWidth: 1.7, strokeLinecap: "round", strokeLinejoin: "round" };
  switch (ic) {
    case "mo":   return <span className="mo">Mo</span>;
    case "pl":   return <svg viewBox="0 0 24 24" {...s}><rect x="4" y="4" width="16" height="16" rx="2" /><rect x="8" y="8" width="8" height="8" rx="1" /></svg>;
    case "brief":return <svg viewBox="0 0 24 24" {...s}><rect x="3" y="7" width="18" height="13" rx="2" /><path d="M8 7V5a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" /></svg>;
    case "cash": return <svg viewBox="0 0 24 24" {...s}><rect x="2" y="6" width="20" height="12" rx="2" /><circle cx="12" cy="12" r="2.4" /></svg>;
    case "sat":  return <svg viewBox="0 0 24 24" {...s}><path d="M5 19a8 8 0 0 1 8-8" /><path d="M5 14a4 4 0 0 1 4 4" /><circle cx="5.5" cy="18.5" r="1.4" fill="currentColor" stroke="none" /><path d="M14 4l6 6-3 3-6-6z" /></svg>;
    case "ai":   return <svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 2.6c1.2 0 2.2.7 2.7 1.7a3 3 0 0 1 2.9 4.9 3 3 0 0 1 0 3.8 3 3 0 0 1-2.9 4.9A3 3 0 0 1 12 21.4a3 3 0 0 1-2.7-1.7 3 3 0 0 1-2.9-4.9 3 3 0 0 1 0-3.8 3 3 0 0 1 2.9-4.9A3 3 0 0 1 12 2.6Zm0 4.4a5 5 0 1 0 0 10 5 5 0 0 0 0-10Z"/></svg>;
    case "route":return <svg viewBox="0 0 24 24" {...s}><path d="M5 4v6a4 4 0 0 0 4 4h10" /><path d="M16 11l4 3-4 3" /></svg>;
    case "sf":   return <svg viewBox="0 0 24 24" fill="currentColor"><path d="M10 7a4 4 0 0 1 7.5-1.4A3.5 3.5 0 0 1 20 12a3.2 3.2 0 0 1-1.2 2.5A3 3 0 0 1 16 17H8a3.5 3.5 0 0 1-.9-6.9A4 4 0 0 1 10 7Z"/></svg>;
    default:     return null;
  }
}
function AppTile({ prov, style }) {
  const p = window.CLAY.PROV[prov];
  if (!p) return null;
  return <span className="clay2-app" style={{ background: p.bg, color: p.fg, ...style }}><ProvGlyph ic={p.ic} /></span>;
}

function Check() { return <span className="chk"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3.2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12.5l4.5 4.5L19 7" /></svg></span>; }

/* ---------- avatar (real photo w/ initials fallback) ---------- */
const AV_BG = ["#E0379E", "#37D6D6", "#52C964", "#6E7BE6", "#0B0B0F"];
function Avatar({ person, cls = "clay2-ava", size }) {
  const [err, setErr] = useState(false);
  const initials = (person.first[0] + person.last[0]).toUpperCase();
  const bg = AV_BG[(person.img + person.first.length) % AV_BG.length];
  const st = size ? { width: size, height: size } : null;
  if (err) return <span className={cls} style={{ background: bg, ...st }}>{initials}</span>;
  return <img className={cls} style={st} src={`https://i.pravatar.cc/96?img=${person.img}`} alt="" onError={() => setErr(true)} />;
}

/* ---------- shared cells ---------- */
function PersonCell({ person }) {
  return (
    <div className="clay2-person">
      <Avatar person={person} />
      <div style={{ minWidth: 0 }}>
        <div className="nm">{person.first} {person.last}</div>
        <div className="co">{person.domain}</div>
      </div>
    </div>
  );
}

/* phase: 'empty' | 'run' | 'done' */
function StatusCell({ col, person, phase }) {
  if (phase === "empty") return <div className="clay2-cell"><span className="clay2-empty" /></div>;
  if (phase === "run")   return <div className="clay2-cell"><span className="clay2-spin" /><span className="clay2-run-pct">running…</span></div>;
  let txt = col.done;
  if (Array.isArray(col.done)) {
    const idx = col.key === "newsT" ? person.newsT : col.key === "jobsT" ? person.jobsT : col.key === "fundT" ? person.fundT : 0;
    txt = col.done[idx];
  }
  return <div className="clay2-cell"><span className="clay2-stat"><Check />{txt}</span></div>;
}

function SignalCell({ person, phase }) {
  if (phase !== "done") return <div className="clay2-sig"><span className="clay2-empty" /></div>;
  const [, label] = person.sig.split(/: (.+)/);
  return (
    <div className="clay2-sig">
      <AppTile prov="signal" />
      <span className="stx"><b>News:</b> {label}</span>
    </div>
  );
}

function ScoreCell({ fit, phase }) {
  const tone = fit >= 80 ? "high" : fit >= 60 ? "mid" : "low";
  if (phase !== "done") return <div className="clay2-cell"><span className="clay2-empty" /></div>;
  return (
    <div className="clay2-cell">
      <span className={"clay2-score " + tone}><span className="bar"><i style={{ width: fit + "%" }} /></span>{fit}</span>
    </div>
  );
}

function TierChip({ tier, phase }) {
  const t = window.CLAY.TIERS[tier];
  if (phase !== "done") return <div className="clay2-cell"><span className="clay2-empty" /></div>;
  return <div className="clay2-cell"><span className={"clay2-tier " + t.tone}>{t.label}</span></div>;
}

function RouteGlyph({ route }) {
  const r = window.CLAY.ROUTES[route];
  if (r.glyph === "sf") return <RouteSF />;
  return <span style={{ fontSize: 12 }}>{r.glyph}</span>;
}
function RouteSF() { return <svg viewBox="0 0 24 24" fill="currentColor"><path d="M10 7a4 4 0 0 1 7.5-1.4A3.5 3.5 0 0 1 20 12a3.2 3.2 0 0 1-1.2 2.5A3 3 0 0 1 16 17H8a3.5 3.5 0 0 1-.9-6.9A4 4 0 0 1 10 7Z"/></svg>; }
function RouteCell({ route, pending, lock }) {
  const r = window.CLAY.ROUTES[route];
  return (
    <div className={"clay2-route" + (pending ? " pending" : "")}>
      <span className={"rg" + (lock ? " lock" : "")} style={{ background: r.color }}><RouteGlyph route={route} /></span>
      <span className="rl">{r.label}</span>
    </div>
  );
}

/* ---------- frame chrome ---------- */
function FrameBar({ rows }) {
  const ncol = window.CLAY.COLUMNS.length;
  return (
    <>
      <div className="clay2-bar">
        <img className="claylogo" src={(window.__resources || {}).clayLogo || "assets/clay-logo.png"} alt="Clay" />
        <span className="live"><span className="ld" /> Live · auto-runs</span>
      </div>
      <div className="clay2-tools">
        <span className="clay2-tool">Default view <span className="cv">▾</span></span>
        <span className="clay2-tool"><svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" strokeWidth="1.8"><path d="M3 5h18l-7 8v6l-4-2v-4z"/></svg> Filter</span>
        <span className="clay2-tool"><svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" strokeWidth="1.8"><path d="M4 7h12M4 12h8M4 17h4M17 5v12M17 17l3-3M17 17l-3-3"/></svg> Sort</span>
        <span className="clay2-tool rowct spacer">{rows}/{rows} rows · {ncol} columns</span>
      </div>
    </>
  );
}

function HeaderRow({ colState, accent, widthTotal }) {
  const cols = window.CLAY.COLUMNS;
  const st = colState || (() => "idle");
  const wstyle = (c) => widthTotal ? { width: (c.w / widthTotal * 100).toFixed(3) + "%" } : { minWidth: c.w, width: c.w };
  return (
    <thead>
      <tr>
        {cols.map((c, i) => {
          const s = c.run ? st(c.key) : "idle";
          return (
            <th key={c.key} style={wstyle(c)}>
              <div className="clay2-th">
                {c.prov ? <AppTile prov={c.prov} /> : null}
                <span className="lbl">{c.label}</span>
                {c.run && (
                  s === "run"
                    ? <span className="run spin" style={{ borderColor: accent, color: accent }}><span className="runring" style={{ borderTopColor: accent }} /></span>
                    : <span className={"run" + (s === "done" ? " done" : "")} style={s === "done" ? { background: accent, color: "#fff", borderColor: "transparent" } : null}>
                        <svg viewBox="0 0 24 24" width="11" height="11" fill="currentColor"><path d="M7 5l11 7-11 7z" /></svg>
                      </span>
                )}
              </div>
            </th>
          );
        })}
      </tr>
    </thead>
  );
}

/* ---------- scroll hooks ---------- */
/* pinned progress 0..1 over a tall track */
function useScrollProgress(travelVh = 280) {
  const ref = useRef(null);
  const [p, setP] = useState(0);
  useEffect(() => {
    let raf = 0;
    const onScroll = () => {
      if (raf) return;
      raf = requestAnimationFrame(() => {
        raf = 0;
        const el = ref.current; if (!el) return;
        const r = el.getBoundingClientRect();
        const vh = window.innerHeight || 800;
        const total = r.height - vh;
        const prog = total > 0 ? Math.min(1, Math.max(0, -r.top / total)) : 0;
        setP(prog);
      });
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll);
    return () => { window.removeEventListener("scroll", onScroll); window.removeEventListener("resize", onScroll); if (raf) cancelAnimationFrame(raf); };
  }, []);
  return [ref, p];
}

/* reveal-once when element enters viewport */
function useInViewOnce(threshold = 0.25) {
  const ref = useRef(null);
  const [seen, setSeen] = useState(false);
  useEffect(() => {
    const el = ref.current; if (!el) return;
    const obs = new IntersectionObserver((es) => {
      es.forEach((e) => { if (e.isIntersecting) { setSeen(true); obs.disconnect(); } });
    }, { threshold });
    obs.observe(el);
    return () => obs.disconnect();
  }, []);
  return [ref, seen];
}

window.CK = {
  AppTile, Check, Avatar, PersonCell, StatusCell, SignalCell, ScoreCell, TierChip,
  RouteCell, RouteGlyph, FrameBar, HeaderRow, useScrollProgress, useInViewOnce,
};
