/* =============================================================
   page-sites.jsx — Searchable site directory
   ============================================================= */
function PageSites({ model, onOpenSite }) {
  const { sites } = model;
  const [search, setSearch] = React.useState("");
  const [filters, setFilters] = React.useState({});

  const opts = React.useMemo(() => {
    return {
      region: PRData.uniqueValues(sites, "region"),
      country: PRData.uniqueValues(sites, "country"),
      criticality: PRData.uniqueValues(sites, "criticality"),
      classification: PRData.uniqueValues(sites, "classification"),
    };
  }, [sites]);

  const filtered = React.useMemo(() => {
    const s = search.trim().toLowerCase();
    return sites.filter((site) => {
      if (filters.region && site.region !== filters.region) return false;
      if (filters.country && site.country !== filters.country) return false;
      if (filters.criticality && site.criticality !== filters.criticality) return false;
      if (filters.classification && site.classification !== filters.classification) return false;
      if (filters._phase) {
        const p = (site.lifecycle && site.lifecycle.lifecyclePhase) || "no-data";
        if (p !== filters._phase) return false;
      }
      if (s) {
        const hay = [site.siteName, site.siteCode, site.shortLabel, site.country, site.region, site.me].join(" ").toLowerCase();
        if (!hay.includes(s)) return false;
      }
      return true;
    });
  }, [sites, filters, search]);

  // Stats
  const stats = PRData.siteStats(filtered);

  // G2: lifecycle phase distribution across the filtered set
  const lifecycleCounts = React.useMemo(() => {
    const m = { complete: 0, "overlay-migrated": 0, "overlay-scheduled": 0, "overlay-ready": 0, "underlay-activated": 0, "underlay-delivery": 0, "underlay-ordering": 0, "underlay-not-started": 0, "isp-termination": 0, blocked: 0, "no-data": 0 };
    for (const s of filtered) {
      const p = (s.lifecycle && s.lifecycle.lifecyclePhase) || "no-data";
      m[p] = (m[p] || 0) + 1;
    }
    return m;
  }, [filtered]);
  const phaseFilter = filters._phase || "";

  const columns = [
    { key: "siteCode", label: "Code", width: 130, cellClass: "mono", render: (r) => r.siteCode || <span className="muted">—</span> },
    { key: "siteName", label: "Site", render: (r) => (
        <div style={{display:"flex", flexDirection: "column"}}>
          <span className="strong">{r.siteName || "—"}</span>
          <span className="muted" style={{fontSize: 11}}>{window.COUNTRY_ISO.canonical(r.country) || "—"} · {r.region}</span>
        </div>
      )},
    { key: "criticality", label: "Crit.", width: 70, render: (r) => <CriticalityPill value={r.criticality}/> },
    { key: "classification", label: "Type", width: 110, render: (r) => r.classification || <span className="muted">—</span> },
    { key: "techno", label: "TECHNO", width: 130, render: (r) => r.techno ? <Pill kind="info">{r.techno}</Pill> : <span className="muted">—</span> },
    { key: "links", label: "Links", width: 60, cellClass: "num",
      render: (r) => (r.canonicalLinkRefs || r.linkRefs || r.links || []).length,
      sortVal: (r) => (r.canonicalLinkRefs || r.linkRefs || r.links || []).length },
    { key: "activated", label: "Activated", width: 90, cellClass: "num",
      render: (r) => {
        const total = (r.canonicalLinkRefs || r.linkRefs || r.links || []).length;
        const a = PRData.siteActivatedLinks(r);
        return <span style={{color: a === total && total ? "var(--ok)" : "var(--ink-700)"}}>{a}/{total}</span>;
      },
      sortVal: (r) => PRData.siteActivatedLinks(r)
    },
    { key: "lifecycle", label: "Lifecycle phase", width: 170,
      render: (r) => r.lifecycle && window.LifecyclePhasePill
        ? <LifecyclePhasePill phase={r.lifecycle.lifecyclePhase} percent={r.lifecycle.lifecyclePercent} compact/>
        : <span className="muted">—</span>,
      sortVal: (r) => r.lifecycle && typeof r.lifecycle.lifecyclePercent === "number" ? r.lifecycle.lifecyclePercent : -1 },
    { key: "migration", label: "Migration", width: 130,
      render: (r) => r.overlay ? <StatusCell value={r.overlay.migrationStatus || r.overlay.migrationSchedule} kind="task"/> : <span className="muted">—</span>,
      sortVal: (r) => r.overlay ? (r.overlay.migrationStatus || r.overlay.migrationSchedule) : "" },
    { key: "risk", label: "Risk", width: 100,
      render: (r) => {
        const anyRisk = r.links.some(PRData.isRiskLink);
        const anyBlock = r.links.some((u) => u.blocker);
        if (anyRisk) return <Pill kind="risk">At risk</Pill>;
        if (anyBlock) return <Pill kind="warn">Blocker</Pill>;
        return <Pill kind="muted">—</Pill>;
      },
      sortVal: (r) => r.links.some(PRData.isRiskLink) ? 2 : r.links.some((u) => u.blocker) ? 1 : 0
    },
    { key: "relationshipWarnings", label: "Warnings", width: 120, render: (r) => <RelationshipWarningCell row={r}/>, sortVal: (r) => (r._relationshipWarnings || []).length },
  ];

  return (
    <div className="page">
      <PageHeader
        title="Sites"
        subtitle="Every site in scope — searchable, filterable, and drillable."
        right={<SearchInput value={search} onChange={setSearch} placeholder="Search site code, name, country…"/>}
      />

      <div className="grid g-4 mb-md">
        <KPI accent label="Sites in view" value={filtered.length.toLocaleString()} hint={`of ${sites.length}`}/>
        <KPI label="Links across sites" value={stats.totalLinks.toLocaleString()} hint="underlay total"/>
        <KPI label="With overlay record" value={stats.sitesWithOverlay.toLocaleString()} hint={`${Math.round((stats.sitesWithOverlay/Math.max(1,filtered.length))*100)}%`}/>
        <KPI label="Migrated" value={stats.migrated.toLocaleString()} hint=""/>
      </div>

      <div className="flex gap-sm mb-md" style={{flexWrap: "wrap"}}>
        <FilterSelect label="Region" value={filters.region} onChange={(v) => setFilters({...filters, region: v})} options={opts.region}/>
        <FilterSelect label="Country" value={filters.country} onChange={(v) => setFilters({...filters, country: v})}
          options={opts.country.map((c) => ({ value: c, label: window.COUNTRY_ISO.canonical(c) }))}/>
        <FilterSelect label="Type" value={filters.classification} onChange={(v) => setFilters({...filters, classification: v})} options={opts.classification}/>
        <FilterSelect label="Criticality" value={filters.criticality} onChange={(v) => setFilters({...filters, criticality: v})} options={opts.criticality}/>
        <FilterSelect label="Lifecycle phase" value={phaseFilter} onChange={(v) => setFilters({...filters, _phase: v})} options={[
          { value: "complete", label: "complete" },
          { value: "overlay-migrated", label: "overlay-migrated" },
          { value: "overlay-scheduled", label: "overlay-scheduled" },
          { value: "overlay-ready", label: "overlay-ready" },
          { value: "underlay-activated", label: "underlay-activated" },
          { value: "underlay-delivery", label: "underlay-delivery" },
          { value: "underlay-ordering", label: "underlay-ordering" },
          { value: "underlay-not-started", label: "underlay-not-started" },
          { value: "isp-termination", label: "isp-termination" },
          { value: "blocked", label: "blocked" },
          { value: "no-data", label: "no-data" },
        ]}/>
        {(filters.region||filters.country||filters.classification||filters.criticality||filters._phase||search) && (
          <button className="btn ghost" onClick={() => { setFilters({}); setSearch(""); }} style={{fontSize: 11.5}}>Clear all</button>
        )}
      </div>

      <div className="flex gap-sm mb-md" style={{flexWrap: "wrap", fontSize: 11.5}}>
        <span style={{color: "var(--ink-500)", textTransform: "uppercase", letterSpacing: "0.06em", marginRight: 6}}>Lifecycle distribution</span>
        {Object.entries(lifecycleCounts).filter(([, n]) => n > 0).map(([phase, n]) => (
          <button key={phase}
            className="btn ghost"
            style={{
              padding: "2px 10px", borderRadius: 999, fontSize: 11,
              background: phase === phaseFilter ? "var(--accent-soft)" : undefined,
            }}
            onClick={() => setFilters({...filters, _phase: phase === phaseFilter ? "" : phase})}>
            {phase} <span className="mono" style={{marginLeft: 4, opacity: 0.7}}>{n}</span>
          </button>
        ))}
      </div>

      <div className="table-wrap">
        <div className="table-toolbar">
          <span className="mono" style={{fontSize: 11.5, color: "var(--ink-500)"}}>{filtered.length.toLocaleString()} sites</span>
        </div>
        <DataTable columns={columns} rows={filtered} onRowClick={(r) => onOpenSite({ site: r })} maxHeight={"70vh"}/>
      </div>
    </div>
  );
}

window.PageSites = PageSites;
