/* ============================================================
   FacilityOS — Analytics screen
   ============================================================ */
window.Screens = window.Screens || {};

Screens.Analytics = function Analytics({ go }) {
  const DB = window.DB;
  const { Card, KpiCard, SectionHead } = UI;
  const { Donut, Legend, HBars, ColumnLine, Gauge, Heatmap, StackedBar } = Charts;
  const [tab, setTab] = useState("overview");

  return (
    <div className="page fade-up">
      <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 18, flexWrap: "wrap" }}>
        <UI.Segmented value={tab} onChange={setTab}
          options={[{ key: "overview", label: "Overview" }, { key: "maintenance", label: "Maintenance" }, { key: "duration", label: "Duration" }, { key: "financial", label: "Financial" }]} />
        <div style={{ marginLeft: "auto", display: "flex", gap: 8 }}>
          <UI.Button variant="default" icon="calendar" size="md">Last 6 months</UI.Button>
          <UI.Button variant="soft" icon="download" size="md">Export</UI.Button>
        </div>
      </div>

      {tab === "overview" && (
        <div style={{ display: "flex", flexDirection: "column", gap: 18 }} key="ov">
          <div className="kpi-grid" style={{ display: "grid", gridTemplateColumns: "repeat(4, minmax(0,1fr))", gap: 16 }}>
            <KpiCard icon="wrench" token="--c-info" label="Total work orders" value="432" delta={11} deltaGood spark={DB.woVolume} />
            <KpiCard icon="check" token="--c-done" label="Completion rate" value="89" suffix="%" delta={4} deltaGood spark={[81,83,84,86,88,89]} />
            <KpiCard icon="clock" token="--accent" label="Avg response time" value="3.2" suffix="h" delta={-14} deltaGood spark={DB.responseHrs} />
            <KpiCard icon="gauge" token="--c-violet" label="PM compliance" value="92" suffix="%" delta={3} deltaGood spark={[85,87,88,90,91,92]} />
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "minmax(0,1.6fr) minmax(0,1fr)", gap: 18, alignItems: "start" }} className="dash-grid">
            <Card>
              <SectionHead title="Work order volume & response time" sub="Created per month vs. avg response (hrs)" />
              <ColumnLine labels={DB.months} bars={DB.woVolume} line={DB.responseHrs} barLabel="WOs created" lineLabel="Avg response (h)" h={230} />
            </Card>
            <Card>
              <SectionHead title="By priority" sub="Open + in-progress" />
              <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 18 }}>
                <Donut data={DB.byPriority} centerValue="88" centerLabel="active" />
                <div style={{ width: "100%" }}><Legend data={DB.byPriority} vertical /></div>
              </div>
            </Card>
          </div>
        </div>
      )}

      {tab === "maintenance" && (
        <div style={{ display: "flex", flexDirection: "column", gap: 18 }} key="mt">
          <div style={{ display: "grid", gridTemplateColumns: "minmax(0,1fr) minmax(0,1fr)", gap: 18 }} className="dash-grid">
            <Card>
              <SectionHead title="Work orders by facility" />
              <HBars data={DB.byFacility} />
            </Card>
            <Card>
              <SectionHead title="PM compliance by facility" sub="Preventive tasks completed on time" />
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-around", flexWrap: "wrap", gap: 16 }}>
                <Gauge value={92} token="--c-done" label="Overall" />
                <div style={{ display: "flex", flexDirection: "column", gap: 12, minWidth: 180, flex: 1 }}>
                  {[{l:"St. Maria Regional",v:96,t:"--c-done"},{l:"The Verona Apts",v:91,t:"--c-done"},{l:"Lincoln Elementary",v:88,t:"--c-medium"},{l:"Maplewood",v:84,t:"--c-medium"},{l:"Cedar Ridge HOA",v:78,t:"--c-high"}].map(x=>(
                    <div key={x.l}>
                      <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12.5, marginBottom: 4 }}><span style={{ color: "var(--text-muted)", fontWeight: 500 }}>{x.l}</span><span className="tnum" style={{ fontWeight: 700 }}>{x.v}%</span></div>
                      <div style={{ height: 7, borderRadius: 99, background: "var(--surface-3)", overflow: "hidden" }}><div style={{ height: "100%", width: `${x.v}%`, background: `var(${x.t})`, borderRadius: 99 }} /></div>
                    </div>
                  ))}
                </div>
              </div>
            </Card>
          </div>
          <Card>
            <SectionHead title="Work orders by category" />
            <div style={{ marginBottom: 14 }}>
              <StackedBar data={[
                { label: "HVAC", value: 28, token: "--c-info" },
                { label: "Plumbing", value: 22, token: "--accent" },
                { label: "Electrical", value: 19, token: "--c-medium" },
                { label: "Structural", value: 14, token: "--c-violet" },
                { label: "Fire Safety", value: 9, token: "--c-critical" },
                { label: "Other", value: 8, token: "--c-low" },
              ]} height={16} />
            </div>
            <Legend data={[
              { label: "HVAC", value: 28, token: "--c-info" },
              { label: "Plumbing", value: 22, token: "--accent" },
              { label: "Electrical", value: 19, token: "--c-medium" },
              { label: "Structural", value: 14, token: "--c-violet" },
              { label: "Fire Safety", value: 9, token: "--c-critical" },
              { label: "Other", value: 8, token: "--c-low" },
            ]} />
          </Card>
        </div>
      )}

      {tab === "duration" && (
        <div style={{ display: "flex", flexDirection: "column", gap: 18 }} key="dr">
          <div className="kpi-grid" style={{ display: "grid", gridTemplateColumns: "repeat(3, minmax(0,1fr))", gap: 16 }}>
            <KpiCard icon="clock" token="--accent" label="Avg time to complete" value="26.4" suffix="h" delta={-9} deltaGood />
            <KpiCard icon="zap" token="--c-critical" label="Avg time to first response" value="3.2" suffix="h" delta={-14} deltaGood />
            <KpiCard icon="check" token="--c-done" label="SLA met" value="94" suffix="%" delta={2} deltaGood />
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "minmax(0,1fr) minmax(0,1fr)", gap: 18 }} className="dash-grid">
            <Card>
              <SectionHead title="Avg completion time by priority" sub="Hours from open to resolved" />
              <HBars data={DB.durationByPriority} unit="h" />
            </Card>
            <Card>
              <SectionHead title="Activity heatmap" sub="When work orders are completed" />
              <Heatmap days={DB.heatDays} rows={DB.heat} token="--accent" />
            </Card>
          </div>
          <Card>
            <SectionHead title="Monthly completion trend" sub="Created vs. completed per month" />
            <ColumnLine labels={DB.months} bars={DB.woVolume} line={DB.completed} barToken="--c-info" lineToken="--c-done" barLabel="Created" lineLabel="Completed" h={220} />
          </Card>
        </div>
      )}

      {tab === "financial" && (
        <div style={{ display: "flex", flexDirection: "column", gap: 18 }} key="fn">
          <div className="kpi-grid" style={{ display: "grid", gridTemplateColumns: "repeat(4, minmax(0,1fr))", gap: 16 }}>
            <KpiCard icon="dollar" token="--c-done" label="Maintenance spend (MTD)" value="$48.2k" delta={6} deltaGood={false} />
            <KpiCard icon="wrench" token="--c-info" label="Avg cost per WO" value="$612" delta={-3} deltaGood />
            <KpiCard icon="box" token="--c-high" label="Parts & materials" value="$19.1k" delta={9} deltaGood={false} />
            <KpiCard icon="clock" token="--accent" label="Labor hours" value="318" suffix="h" delta={4} deltaGood={false} />
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "minmax(0,1.6fr) minmax(0,1fr)", gap: 18, alignItems: "start" }} className="dash-grid">
            <Card>
              <SectionHead title="Monthly spend" sub="Labor + parts, thousands USD" />
              <ColumnLine labels={DB.months} bars={[38,41,44,46,52,48]} line={[31,33,36,37,42,40]} barToken="--c-done" lineToken="--c-high" barLabel="Total spend" lineLabel="Labor only" h={230} />
            </Card>
            <Card>
              <SectionHead title="Spend by facility" />
              <HBars data={[
                { label: "St. Maria Regional", value: 18.4, token: "--c-info" },
                { label: "The Verona Apts", value: 11.2, token: "--accent" },
                { label: "Lincoln Elementary", value: 8.6, token: "--c-violet" },
                { label: "Maplewood", value: 6.3, token: "--c-medium" },
                { label: "Cedar Ridge HOA", value: 3.7, token: "--c-done" },
              ]} unit="k" />
            </Card>
          </div>
        </div>
      )}
    </div>
  );
};
