// ui.jsx — shared presentational components
const { useState, useEffect, useRef } = React;

const STATUS_LABEL = {
  new: "New", reviewed: "Reviewed", approved: "Approved",
  rejected: "Rejected", exported: "Exported", synced: "Synced to CRM",
};
const STATUS_CLASS = {
  new: "b-new", reviewed: "b-reviewed", approved: "b-approved",
  rejected: "b-rejected", exported: "b-exported", synced: "b-synced",
};

function StatusBadge({ status }) {
  return <span className={"badge " + (STATUS_CLASS[status] || "b-gray")}>{STATUS_LABEL[status] || status}</span>;
}

function scoreTier(n) { return n >= 85 ? "s-high" : n >= 70 ? "s-mid" : "s-low"; }

function ScoreMeter({ value, showBar = true }) {
  return (
    <div className={"score " + scoreTier(value)}>
      <span className="score-num">{value}</span>
      {showBar && <span className="score-bar"><span className="score-fill" style={{ width: value + "%" }} /></span>}
    </div>
  );
}

function CompanyLogo({ name, size = 30 }) {
  return (
    <span className="co-logo" style={{ background: logoFor(name), width: size, height: size, fontSize: size*0.4 }}>
      {initials(name)}
    </span>
  );
}

function Checkbox({ checked, onChange, indeterminate }) {
  return (
    <span className={"cbx " + (checked || indeterminate ? "on" : "")} onClick={(e) => { e.stopPropagation(); onChange && onChange(!checked); }}>
      {indeterminate
        ? <svg width="12" height="12" viewBox="0 0 24 24"><path d="M6 12h12" stroke="#fff" strokeWidth="3" strokeLinecap="round"/></svg>
        : <Icon name="check" size={11} color="#fff" strokeWidth={3} />}
    </span>
  );
}

function SourceTag({ source }) {
  const m = (window.SOURCES_META || {})[source] || { color: "#64748b", short: "··" };
  return (
    <span className="row gap-6" style={{ fontSize: 12.5 }}>
      <span style={{ width: 18, height: 18, borderRadius: 5, background: m.color, color: "#fff", display: "grid", placeItems: "center", fontSize: 9, fontWeight: 700, flexShrink: 0 }}>{m.short}</span>
      <span className="muted">{source}</span>
    </span>
  );
}

function Stat({ label, value, delta, deltaDir, icon, sub }) {
  return (
    <div className="stat">
      <div className="stat-label">{icon && <Icon name={icon} size={14} color="var(--gray-400)" />}{label}</div>
      <div className="stat-val">{value}</div>
      {delta != null && (
        <div className={"stat-delta " + (deltaDir === "up" ? "delta-up" : deltaDir === "down" ? "delta-down" : "delta-flat")}>
          {deltaDir === "up" && <Icon name="arrowUp" size={12} />}
          {deltaDir === "down" && <Icon name="arrowDown" size={12} />}
          {delta}{sub && <span className="muted" style={{ fontWeight: 400, marginLeft: 2 }}>{sub}</span>}
        </div>
      )}
    </div>
  );
}

function Confidence({ value }) {
  const pct = Math.round(value * 100);
  const c = value >= 0.85 ? "var(--green)" : value >= 0.7 ? "var(--amber)" : "var(--gray-400)";
  return (
    <span className="row gap-6" title={"Source confidence " + pct + "%"}>
      <span style={{ width: 38, height: 6, borderRadius: 4, background: "var(--gray-200)", overflow: "hidden", display: "inline-block" }}>
        <span style={{ display: "block", height: "100%", width: pct + "%", background: c }} />
      </span>
      <span className="mono" style={{ color: "var(--gray-500)" }}>{pct}%</span>
    </span>
  );
}

function Toast({ msg, onDone }) {
  useEffect(() => { const t = setTimeout(onDone, 2600); return () => clearTimeout(t); }, []);
  return <div className="toast"><Icon name="check" size={15} color="var(--green)" strokeWidth={2.6} />{msg}</div>;
}

function Empty({ icon = "leads", title, sub }) {
  return (
    <div className="empty">
      <Icon name={icon} size={34} color="var(--gray-300)" />
      <div style={{ fontWeight: 600, color: "var(--gray-600)", fontSize: 15 }}>{title}</div>
      {sub && <div style={{ marginTop: 4, fontSize: 13 }}>{sub}</div>}
    </div>
  );
}

// Simple bar chart for reporting
function BarChart({ data, valueKey, secondKey, height = 130 }) {
  const max = Math.max(...data.map(d => d[valueKey])) || 1;
  return (
    <div className="chart" style={{ height }}>
      {data.map((d, i) => (
        <div key={i} style={{ flex: 1, height: "100%", display: "flex", flexDirection: "column", justifyContent: "flex-end", alignItems: "center", gap: 5, minWidth: 0 }}>
          <div style={{ width: "100%", display: "flex", gap: 2, alignItems: "flex-end", flex: 1 }}>
            <div className="bar" style={{ height: (d[valueKey]/max*100) + "%" }}>
              <span className="tip">{d[valueKey]} found{secondKey ? ` · ${d[secondKey]} approved` : ""}</span>
            </div>
            {secondKey && <div className="bar" style={{ height: (d[secondKey]/max*100) + "%", background: "var(--accent)" }} />}
          </div>
          <span style={{ fontSize: 10.5, color: "var(--gray-400)", whiteSpace: "nowrap" }}>{d.label}</span>
        </div>
      ))}
    </div>
  );
}

function fmtNum(n) {
  if (n >= 1e6) return (n/1e6).toFixed(n >= 1e7 ? 0 : 1) + "M";
  if (n >= 1e3) return (n/1e3).toFixed(n >= 1e4 ? 0 : 1) + "K";
  return String(n);
}

Object.assign(window, {
  StatusBadge, ScoreMeter, CompanyLogo, Checkbox, SourceTag, Stat,
  Confidence, Toast, Empty, BarChart, scoreTier, fmtNum,
  STATUS_LABEL, STATUS_CLASS,
});
