"use client";

/**
 * Lead funnel analytics — daily trend + branch bars, role-scoped.
 */

import { useEffect, useState } from "react";
import { AppShell } from "@/components/AppShell";
import { api } from "@/lib/api";

type Funnel = {
  daily: { day: string; total: number }[];
  by_branch: { branch: string; total: number }[];
  total: number;
};

export default function AnalyticsPage() {
  const [data, setData] = useState<Funnel | null>(null);
  const [error, setError] = useState("");

  useEffect(() => {
    api<{ data: Funnel }>("/analytics/lead-funnel")
      .then((res) => setData(res.data))
      .catch((err) => setError(err instanceof Error ? err.message : "Failed"));
  }, []);

  const maxDaily = Math.max(1, ...(data?.daily.map((d) => Number(d.total)) || [1]));
  const maxBranch = Math.max(1, ...(data?.by_branch.map((d) => Number(d.total)) || [1]));

  return (
    <AppShell>
      <div className="ps-page rise">
        <header className="ps-page-header">
          <div>
            <h1 className="ps-page-title">Lead Analytics</h1>
            <p className="ps-page-sub">Funnel twin for lead boards · role scoped</p>
          </div>
        </header>

        {error ? <div className="alloc-alert alloc-alert-err">{error}</div> : null}

        <div className="ps-card ps-card-static" style={{ padding: "1.15rem" }}>
          <div style={{ color: "var(--muted)", fontSize: "0.9rem", fontWeight: 600 }}>Total leads in scope</div>
          <div style={{ fontFamily: "var(--font-display)", fontSize: "2.35rem", letterSpacing: "-0.02em" }}>
            {data?.total ?? "—"}
          </div>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1.2fr 1fr", gap: "0.9rem" }}>
          <div className="ps-card ps-card-static" style={{ padding: "1.15rem", display: "grid", gap: "0.7rem" }}>
            <h3 style={{ margin: 0 }}>Daily trend</h3>
            {(data?.daily || []).map((row, i) => (
              <div key={row.day}>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: "0.9rem", marginBottom: 4 }}>
                  <span>{row.day}</span>
                  <strong>{row.total}</strong>
                </div>
                <div style={{ height: 9, borderRadius: 999, background: "rgba(15,23,42,0.06)", overflow: "hidden" }}>
                  <div
                    className="ps-bar"
                    style={{
                      width: `${(Number(row.total) / maxDaily) * 100}%`,
                      height: "100%",
                      borderRadius: 999,
                      background: "linear-gradient(90deg, var(--brand-mid), var(--brand))",
                      animationDelay: `${i * 40}ms`,
                    }}
                  />
                </div>
              </div>
            ))}
            {!data?.daily?.length ? <p className="ps-empty" style={{ padding: "1rem 0" }}>No daily data.</p> : null}
          </div>

          <div className="ps-card ps-card-static" style={{ padding: "1.15rem", display: "grid", gap: "0.7rem" }}>
            <h3 style={{ margin: 0 }}>By branch</h3>
            {(data?.by_branch || []).map((row, i) => (
              <div key={row.branch}>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: "0.9rem", marginBottom: 4 }}>
                  <span>{row.branch}</span>
                  <strong>{row.total}</strong>
                </div>
                <div style={{ height: 9, borderRadius: 999, background: "rgba(15,23,42,0.06)", overflow: "hidden" }}>
                  <div
                    className="ps-bar"
                    style={{
                      width: `${(Number(row.total) / maxBranch) * 100}%`,
                      height: "100%",
                      borderRadius: 999,
                      background: "linear-gradient(90deg, #60a5fa, var(--brand-mid))",
                      animationDelay: `${i * 40}ms`,
                    }}
                  />
                </div>
              </div>
            ))}
            {!data?.by_branch?.length ? <p className="ps-empty" style={{ padding: "1rem 0" }}>No branch data.</p> : null}
          </div>
        </div>
      </div>
    </AppShell>
  );
}
