/* Landing page for the SPIF Tracker.
 *
 * A hub that links out to the four individual SPIF documents. Reads the
 * same shared store (so the summary numbers match each doc) and renders
 * one card per active SPIF.
 */

const SPIF_DOCS = {
  manager:  "Manager SPIF - New Hire Bonus.html",
  csam:     "CSAM SPIF - PBExpo Commission.html",
  csamPres: "CSAM SPIF - Presentation Sprint.html",
  aeDemo:   "AE SPIF - Demo Benchmark Sprint.html",
  catSpiff: "AE SPIF - Customer Acquisitions.html",
  cstSpiff: "CSAM SPIF - Customer Success.html",
  partStore: "Team SPIF - PartStore.html",
};

function Landing() {
  return (
    <StoreProvider>
      <LandingInner />
    </StoreProvider>
  );
}

function LandingInner() {
  const { state, today } = useStore();
  const auth = (typeof useAuth === "function") ? useAuth() : null;
  const showManager = (typeof canSeeManagerSpiff !== "function") || canSeeManagerSpiff(auth && auth.user);
  const totals = useOrgTotals();
  const presTeam = presentationTeamFor(state.csams, state.spiffs.csamPresentations, today);
  const aeTeam = aeDemoTeamFor(state.aes, state.spiffs.aeDemos, today);
  const catTeam = industryTeamFor(state.aes, state.spiffs.catSpiff, today);
  const cstTeam = industryTeamFor(state.csams, state.spiffs.cstSpiff, today);
  const psTeam = partStoreTeamFor(state.aes, state.csams, state.spiffs.partStore, today);

  const peopleTracked = state.managers.length + state.csams.length + state.aes.length;
  const payoutsToDate = totals.manager.earned + totals.csam.commission + catTeam.totalPaid + cstTeam.totalPaid + psTeam.earned;

  const cards = [
    ...(showManager ? [{
      key: "manager",
      audience: "Managers",
      title: state.spiffs.manager.name,
      descriptor: "$500 per qualifying new hire who closes within 120 days.",
      window: `${fmtDate(state.spiffs.manager.eligibilityStart)} – ${fmtDate(state.spiffs.manager.eligibilityEnd)}`,
      metrics: [
        { label: "Qualified", value: `${totals.manager.qualified}/${totals.manager.totalHires}`, accent: "var(--success-700)" },
        { label: "Bonuses earned", value: fmtMoney(totals.manager.earned) },
        { label: "Pending", value: totals.manager.pending, accent: "var(--color-700)" },
      ],
    }] : []),
    {
      key: "csam",
      audience: "CSAMs",
      title: state.spiffs.csam.name,
      descriptor: "25% commission on first-year PBExpo booth sales.",
      window: "Effective immediately · ongoing",
      metrics: [
        { label: "Booth sales", value: totals.csam.sales },
        { label: "Commission", value: fmtMoney(totals.csam.commission), accent: "var(--success-700)" },
        { label: "Reps selling", value: `${totals.csam.repsWithSales}/${totals.csam.reps}` },
      ],
    },
    {
      key: "csamPres",
      audience: "CSAMs",
      title: state.spiffs.csamPresentations.name,
      descriptor: "$250 individual contest plus a $1,000 team pool & ½ day.",
      window: `Contest ${fmtDateShort(state.spiffs.csamPresentations.contestStart)}–${fmtDateShort(state.spiffs.csamPresentations.contestEnd)} · Team to ${fmtDateShort(state.spiffs.csamPresentations.teamEnd)}`,
      metrics: [
        { label: "Team presentations", value: `${presTeam.teamTotal}/${presTeam.target}`, accent: presTeam.achieved ? "var(--success-700)" : "var(--color-800)" },
        { label: "Contest leader", value: presTeam.winner ? presTeam.winner.name.split(" ")[0] : "—", accent: "var(--color-700)" },
        { label: "Eligible reps", value: `${presTeam.eligibleReps}/${state.csams.length}` },
      ],
    },
    {
      key: "aeDemo",
      audience: "AEs",
      title: state.spiffs.aeDemos.name,
      descriptor: "Highest balanced demo attainment across 5 categories wins.",
      window: `${fmtDate(state.spiffs.aeDemos.start)} – ${fmtDate(state.spiffs.aeDemos.end)} · ${state.spiffs.aeDemos.weeks} weeks`,
      metrics: [
        { label: "Team demos", value: `${aeTeam.teamTotal}` },
        { label: aeTeam.status === "upcoming" ? "Starts" : "Week", value: aeTeam.status === "upcoming" ? fmtDateShort(state.spiffs.aeDemos.start) : `${aeTeam.currentWeek + 1}/${state.spiffs.aeDemos.weeks}` },
        { label: "Leader", value: aeTeam.leader ? aeTeam.leader.name.split(" ")[0] : "—", accent: "var(--color-700)" },
      ],
    },
    {
      key: "catSpiff",
      audience: "AEs",
      title: state.spiffs.catSpiff.name,
      descriptor: "PBD-CAT · close 2+ new deals in a qualifying segment by Jun 30.",
      window: `${state.spiffs.catSpiff.code} · ${fmtDate(state.spiffs.catSpiff.start)} – ${fmtDate(state.spiffs.catSpiff.end)}`,
      metrics: [
        { label: "Qualifying closes", value: catTeam.totalDeals },
        { label: "Payouts", value: fmtMoney(catTeam.totalPaid), accent: "var(--success-700)" },
        { label: "Trophy leader", value: catTeam.revLeader ? catTeam.revLeader.name.split(" ")[0] : "—", accent: "var(--color-700)" },
      ],
    },
    {
      key: "cstSpiff",
      audience: "CSAMs",
      title: state.spiffs.cstSpiff.name,
      descriptor: "PBD-CST · full-rate renewals, upgrades & expansions by Jun 30.",
      window: `${state.spiffs.cstSpiff.code} · ${fmtDate(state.spiffs.cstSpiff.start)} – ${fmtDate(state.spiffs.cstSpiff.end)}`,
      metrics: [
        { label: "Renew + upgrade", value: cstTeam.totalDeals },
        { label: "Payouts", value: fmtMoney(cstTeam.totalPaid), accent: "var(--success-700)" },
        { label: "Trophy leader", value: cstTeam.revLeader ? cstTeam.revLeader.name.split(" ")[0] : "—", accent: "var(--color-700)" },
      ],
    },
    {
      key: "partStore",
      audience: "AEs & CSAMs",
      title: state.spiffs.partStore.name,
      descriptor: "Commission activates when the customer lists inventory on PartStore.",
      window: `Sign by ${fmtDate(state.spiffs.partStore.signBy)} · inventory by ${fmtDate(state.spiffs.partStore.inventoryDeadline)}`,
      metrics: [
        { label: "Inventory live", value: psTeam.activatedDeals, accent: "var(--success-700)" },
        { label: "Awaiting", value: psTeam.signedDeals, accent: "var(--warning-700)" },
        { label: "Credited", value: fmtMoney(psTeam.earned), accent: "var(--success-700)" },
      ],
    },
  ];

  return (
    <div style={{ background: "var(--gray-50)", minHeight: "100vh", fontFamily: "var(--font-sans-private)" }}>
      <AppHeader subtitle="All programs" right={
        <>
          <SyncBadge />
          <button className="pb-button pb-button-sm pb-button-primary" style={{ fontSize: 12, padding: "6px 14px" }}>
            <Icon name="plus" size={14} /> New SPIF
          </button>
        </>
      } />

      <div style={{ maxWidth: 1080, margin: "0 auto", padding: "32px 24px 56px" }}>
        {/* Hero */}
        <div style={{ marginBottom: 24 }}>
          <div style={{
            display: "inline-flex", alignItems: "center", gap: 7,
            fontSize: 11, fontWeight: 700, letterSpacing: "0.1em", textTransform: "uppercase",
            color: "var(--color-600)", background: "var(--color-100)",
            padding: "5px 12px", borderRadius: 999, marginBottom: 14,
          }}>
            <svg width="12" height="12" viewBox="0 0 24 24" fill="var(--color-600)"><path d="M12 2L3 7v6c0 5 3.8 8.5 9 9 5.2-.5 9-4 9-9V7l-9-5z"/></svg>
            PartsBase Sales Incentives
          </div>
          <h1 style={{
            margin: 0, fontSize: 30, fontWeight: 700, color: "var(--color-800)",
            letterSpacing: "-0.02em",
          }}>Sales incentive programs</h1>
          <p style={{ fontSize: 14, color: "var(--gray-600)", marginTop: 8, maxWidth: 620, lineHeight: 1.5 }}>
            Track progress across every active SPIF. Open a program to log activity and review individual standings.
          </p>
        </div>

        {/* Overview strip */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 12, marginBottom: 28 }}>
          <StatTile label="Active SPIFs" value={showManager ? "7" : "6"} sub={showManager ? "3 CSAM · 1 Manager · 2 AE · 1 team" : "3 CSAM · 2 AE · 1 team"} />
          <StatTile label="Payouts to date" value={fmtMoney(payoutsToDate)} sub={`${fmtMoney(totals.manager.earned)} bonuses · ${fmtMoney(totals.csam.commission)} commission`} accent="var(--success-700)" />
          <StatTile label="People tracked" value={peopleTracked} sub={`${state.managers.length} managers · ${state.aes.length} AEs · ${state.csams.length} CSAMs`} />
        </div>

        {/* Program cards */}
        <div style={{
          fontSize: 11, fontWeight: 700, letterSpacing: "0.1em", textTransform: "uppercase",
          color: "var(--gray-500)", marginBottom: 12,
        }}>Active programs</div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 16 }} className="spif-card-grid">
          {cards.map(c => <SpifCard key={c.key} card={c} />)}
        </div>
      </div>

      <style>{`
        @media (max-width: 720px) {
          .spif-card-grid { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </div>
  );
}

function SpifCard({ card }) {
  const [hover, setHover] = React.useState(false);
  return (
    <a
      href={encodeURI(SPIF_DOCS[card.key])}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        display: "block", textDecoration: "none",
        background: "#fff",
        border: "1px solid var(--gray-200)",
        borderRadius: 16,
        padding: "20px 22px",
        boxShadow: hover ? "var(--cards-hover, 0 12px 28px rgba(16,121,248,0.16))" : "var(--shadow-xs, 0 1px 2px rgba(16,24,40,0.05))",
        transform: hover ? "translateY(-2px)" : "none",
        transition: "box-shadow 0.18s ease, transform 0.18s ease, border-color 0.18s ease",
        borderColor: hover ? "var(--color-300)" : "var(--gray-200)",
      }}
    >
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
        <span style={{
          fontSize: 11, fontWeight: 700, letterSpacing: "0.06em", textTransform: "uppercase",
          color: "var(--color-600)",
        }}>{card.audience}</span>
        <StatusPill status="active" />
      </div>

      <h3 style={{
        margin: 0, fontSize: 18, fontWeight: 700, color: "var(--color-800)",
        letterSpacing: "-0.01em", lineHeight: 1.2,
      }}>{card.title}</h3>
      <p style={{ fontSize: 13, color: "var(--gray-600)", margin: "8px 0 4px", lineHeight: 1.45, textWrap: "pretty" }}>
        {card.descriptor}
      </p>
      <div style={{ fontSize: 12, color: "var(--gray-500)", fontFeatureSettings: "'tnum'", marginBottom: 16 }}>
        {card.window}
      </div>

      <div style={{
        display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 8,
        padding: "14px 0 4px", borderTop: "1px solid var(--gray-150, var(--gray-100))",
      }}>
        {card.metrics.map((m, i) => (
          <div key={i}>
            <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: "0.05em", textTransform: "uppercase", color: "var(--gray-500)" }}>{m.label}</div>
            <div style={{
              fontSize: 18, fontWeight: 700, marginTop: 3,
              color: m.accent || "var(--color-800)",
              fontFeatureSettings: "'tnum'", lineHeight: 1.1,
            }}>{m.value}</div>
          </div>
        ))}
      </div>

      <div style={{
        display: "flex", alignItems: "center", gap: 6, marginTop: 14,
        fontSize: 13, fontWeight: 600,
        color: hover ? "var(--color-600)" : "var(--gray-600)",
        transition: "color 0.18s ease, gap 0.18s ease",
      }}>
        Open program
        <span style={{ display: "inline-flex", transform: hover ? "translateX(2px)" : "none", transition: "transform 0.18s ease" }}>
          <Icon name="chevron" size={15} />
        </span>
      </div>
    </a>
  );
}

window.Landing = Landing;
