import { useState, useMemo } from "react";

const NAVY = "#0f1f38";
const GOLD = "#c9a84c";
const CREAM = "#f7f3ec";
const MID = "#e8e2d9";
const STEEL = "#4a5568";
const RED = "#c0392b";
const GREEN = "#2d6a4f";
const BLUE = "#1a56a0";
const GREEN_LIGHT = "#e8f5ee";
const RED_LIGHT = "#fdf0ee";
const BLUE_LIGHT = "#eef2fa";
const AMBER_LIGHT = "#fffbeb";
const AMBER = "#b7791f";

const fmt = (n) => "$" + Math.round(n).toLocaleString();

const KPI_CATS = [
  {
    id: "leasing", label: "Leasing", color: BLUE,
    kpis: ["Site visits conducted","LOIs / HOTs issued","PLCs signed","Pipeline CRM accuracy","Renewal / upsell activity","Tenant satisfaction score"],
  },
  {
    id: "bd", label: "BD / Leads", color: RED,
    kpis: ["New qualified leads generated","Broker / ecosystem touchpoints","Market intel reports submitted","Lead-to-visit conversion rate"],
  },
  {
    id: "compliance", label: "Compliance & Reporting", color: GREEN,
    kpis: ["Monday.com updates on time","Regulatory / PCCC follow-up","Internal reporting deadlines","Policy adherence score"],
  },
];

const FORMULAS = {
  A: {
    label: "Option A — Simple",
    tag: "Recommended Year 1",
    desc: "Flat KPI score (weighted average of 3 categories) gates your share of the pool. Simple to explain and administer.",
    calc: ({ poolUSD, roleShare, kpiScores, catWeights }) => {
      const score = kpiScores.leasing * catWeights.leasing + kpiScores.bd * catWeights.bd + kpiScores.compliance * catWeights.compliance;
      return poolUSD * roleShare * Math.min(score, 1.0);
    },
  },
  B: {
    label: "Option B — Weighted KPI",
    tag: "Year 2",
    desc: "Same as A but allows scores above 100% to boost payout up to 120% cap. More precise incentive for outperformers.",
    calc: ({ poolUSD, roleShare, kpiScores, catWeights }) => {
      const score = kpiScores.leasing * catWeights.leasing + kpiScores.bd * catWeights.bd + kpiScores.compliance * catWeights.compliance;
      return poolUSD * roleShare * Math.min(score, 1.2);
    },
  },
  C: {
    label: "Option C — Tiered Gate",
    tag: "Sophisticated",
    desc: "Below 70% = no payout. 70–85% = 70% of share. 85–100% = full share. Above 100% rolls to year-end bonus pool.",
    calc: ({ poolUSD, roleShare, kpiScores, catWeights }) => {
      const score = kpiScores.leasing * catWeights.leasing + kpiScores.bd * catWeights.bd + kpiScores.compliance * catWeights.compliance;
      if (score < 0.7) return 0;
      if (score < 0.85) return poolUSD * roleShare * 0.7;
      return poolUSD * roleShare;
    },
    exceedanceNote: true,
  },
};

const ROLES = [
  { id: "bdHead", label: "BD / Leasing Head" },
  { id: "leasingMgr", label: "Leasing Manager" },
  { id: "cx", label: "CX Executive" },
  { id: "admin", label: "Leasing Admin" },
];

function SliderRow({ label, value, onChange, min = 0, max = 100, step = 1, unit = "%", color = NAVY, note }) {
  return (
    <div style={{ marginBottom: 10 }}>
      <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 2 }}>
        <span style={{ fontSize: 11, fontWeight: 600, color: NAVY }}>{label}</span>
        <span style={{ fontSize: 12, fontWeight: 700, color }}>
          {unit === "$" ? "$" + Number(value).toLocaleString() : value + (unit === "" ? "" : unit)}
        </span>
      </div>
      {note && <div style={{ fontSize: 9.5, color: STEEL, marginBottom: 2 }}>{note}</div>}
      <input type="range" min={min} max={max} step={step} value={value}
        onChange={(e) => onChange(Number(e.target.value))}
        style={{ width: "100%", accentColor: color }} />
    </div>
  );
}

function Card({ children, style = {} }) {
  return <div style={{ background: "white", border: `1px solid ${MID}`, borderRadius: 4, padding: "14px 16px", ...style }}>{children}</div>;
}

function SectionLabel({ children, color = NAVY }) {
  return <div style={{ fontSize: 9.5, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.8px", color, marginBottom: 10, paddingBottom: 5, borderBottom: `2px solid ${GOLD}` }}>{children}</div>;
}

export default function CommissionCalculator() {
  const [enr, setEnr] = useState(15000);
  const [leaseTerm, setLeaseTerm] = useState(36);
  const [leaseType, setLeaseType] = useState("direct");
  const [numDeals, setNumDeals] = useState(3);
  const [formula, setFormula] = useState("A");
  const [activeRole, setActiveRole] = useState("bdHead");

  const [shares, setShares] = useState({ bdHead: 30, leasingMgr: 40, cx: 20, admin: 10 });

  const [kpiScores, setKpiScores] = useState({
    bdHead:     { leasing: 1.0, bd: 1.0, compliance: 1.0 },
    leasingMgr: { leasing: 1.0, bd: 0.8, compliance: 1.0 },
    cx:         { leasing: 0.9, bd: 0.7, compliance: 1.0 },
    admin:      { leasing: 0.8, bd: 0.6, compliance: 1.0 },
  });

  const [catWeights, setCatWeights] = useState({ leasing: 0.5, bd: 0.3, compliance: 0.2 });

  const commissionRate = leaseType === "direct" ? 0.5 : 0.25;
  const commissionPerDeal = enr * leaseTerm * commissionRate;
  const quarterlyPool = commissionPerDeal * numDeals;
  const bdOverride = quarterlyPool * 0.10;
  const ddShare = quarterlyPool * 0.25;
  const remainingPool = quarterlyPool - bdOverride - ddShare;
  const sharesTotal = Object.values(shares).reduce((a, b) => a + b, 0);

  const updateCatWeight = (cat, val) => {
    const frac = val / 100;
    const remaining = 1 - frac;
    const others = Object.keys(catWeights).filter(c => c !== cat);
    const otherTotal = others.reduce((s, c) => s + catWeights[c], 0);
    const nw = { ...catWeights, [cat]: frac };
    if (otherTotal > 0) others.forEach(c => { nw[c] = (catWeights[c] / otherTotal) * remaining; });
    setCatWeights(nw);
  };

  const results = useMemo(() => ROLES.map(role => {
    const roleShare = (shares[role.id] || 0) / 100;
    const scores = kpiScores[role.id];
    const payout = FORMULAS[formula].calc({ poolUSD: remainingPool, roleShare, kpiScores: scores, catWeights });
    const compositeScore = scores.leasing * catWeights.leasing + scores.bd * catWeights.bd + scores.compliance * catWeights.compliance;
    return { ...role, payout, compositeScore };
  }), [shares, kpiScores, catWeights, formula, remainingPool]);

  const getScoreColor = (s) => s >= 1.0 ? GREEN : s >= 0.7 ? BLUE : RED;
  const getScoreBg = (s) => s >= 1.0 ? GREEN_LIGHT : s >= 0.7 ? BLUE_LIGHT : RED_LIGHT;

  return (
    <div style={{ fontFamily: "'DM Sans','Inter',sans-serif", background: CREAM, minHeight: "100vh", padding: "20px 18px", color: NAVY }}>

      {/* Header */}
      <div style={{ borderBottom: `2px solid ${GOLD}`, paddingBottom: 12, marginBottom: 18, display: "flex", justifyContent: "space-between", alignItems: "flex-end" }}>
        <div>
          <div style={{ fontSize: 20, fontWeight: 700, color: NAVY }}>CORE<span style={{ color: GOLD }}>5</span> Commission Calculator</div>
          <div style={{ fontSize: 10, color: STEEL, marginTop: 2 }}>KPI-Linked Pool · Internal Design Tool · v1 · 2026</div>
        </div>
        <div style={{ display: "flex", gap: 5 }}>
          {Object.entries(FORMULAS).map(([k, f]) => (
            <button key={k} onClick={() => setFormula(k)} style={{
              padding: "4px 12px", borderRadius: 3, fontSize: 11, fontWeight: 700, cursor: "pointer", border: "none",
              background: formula === k ? NAVY : "white", color: formula === k ? GOLD : STEEL,
              boxShadow: formula === k ? "none" : `0 0 0 1px ${MID}`
            }}>{k}</button>
          ))}
        </div>
      </div>

      {/* Formula banner */}
      <div style={{ background: NAVY, borderRadius: 4, padding: "10px 14px", marginBottom: 16, display: "flex", gap: 10, alignItems: "flex-start" }}>
        <div style={{ flex: 1 }}>
          <div style={{ display: "flex", gap: 8, alignItems: "center", marginBottom: 3 }}>
            <span style={{ fontSize: 12, fontWeight: 700, color: "white" }}>{FORMULAS[formula].label}</span>
            <span style={{ fontSize: 9, fontWeight: 700, padding: "2px 6px", borderRadius: 2, background: GOLD, color: NAVY }}>{FORMULAS[formula].tag}</span>
          </div>
          <div style={{ fontSize: 11, color: "rgba(255,255,255,0.72)", lineHeight: 1.55 }}>{FORMULAS[formula].desc}</div>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 12 }}>

        {/* COL 1 */}
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          <Card>
            <SectionLabel>Deal Parameters</SectionLabel>
            <SliderRow label="Effective Net Rent / month" value={enr} onChange={setEnr} min={3000} max={100000} step={1000} unit="$" color={BLUE} />
            <SliderRow label="Lease Term" value={leaseTerm} onChange={setLeaseTerm} min={12} max={120} step={6} unit=" mo" color={BLUE} />
            <div style={{ marginBottom: 10 }}>
              <div style={{ fontSize: 11, fontWeight: 600, marginBottom: 5 }}>Lease Type</div>
              <div style={{ display: "flex", gap: 5 }}>
                {[["direct","Direct (50%)"],["indirect","Indirect (25%)"]].map(([t, lab]) => (
                  <button key={t} onClick={() => setLeaseType(t)} style={{
                    flex: 1, padding: "5px 0", borderRadius: 3, fontSize: 10, fontWeight: 700,
                    cursor: "pointer", border: "none",
                    background: leaseType === t ? NAVY : "white", color: leaseType === t ? GOLD : STEEL,
                    boxShadow: leaseType === t ? "none" : `0 0 0 1px ${MID}`
                  }}>{lab}</button>
                ))}
              </div>
            </div>
            <SliderRow label="Deals closing this quarter" value={numDeals} onChange={setNumDeals} min={1} max={10} step={1} unit="" color={BLUE} />
            <div style={{ borderTop: `1px solid ${MID}`, paddingTop: 10, marginTop: 6 }}>
              {[
                ["Commission / deal", fmt(commissionPerDeal)],
                ["Quarterly gross pool", fmt(quarterlyPool)],
                ["BD Override (10%)", fmt(bdOverride)],
                ["Deputy Director (25%)", fmt(ddShare)],
                ["Distributable pool", fmt(remainingPool), true],
              ].map(([lbl, val, bold]) => (
                <div key={lbl} style={{ display: "flex", justifyContent: "space-between", fontSize: 11, padding: "3px 0", borderBottom: lbl === "Quarterly gross pool" ? `1px dashed ${MID}` : "none" }}>
                  <span style={{ color: STEEL }}>{lbl}</span>
                  <span style={{ fontWeight: bold ? 800 : 700, color: bold ? NAVY : STEEL }}>{val}</span>
                </div>
              ))}
            </div>
          </Card>

          <Card>
            <SectionLabel>KPI Category Weights</SectionLabel>
            <div style={{ fontSize: 10, color: STEEL, marginBottom: 8 }}>Auto-balances across categories.</div>
            {KPI_CATS.map(cat => (
              <SliderRow key={cat.id} label={cat.label} value={Math.round(catWeights[cat.id] * 100)} onChange={v => updateCatWeight(cat.id, v)} min={10} max={70} step={5} color={cat.color} />
            ))}
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: 11, marginTop: 4, padding: "4px 8px", background: GREEN_LIGHT, borderRadius: 3 }}>
              <span>Total</span>
              <span style={{ fontWeight: 700, color: GREEN }}>{Math.round(Object.values(catWeights).reduce((s, v) => s + v, 0) * 100)}%</span>
            </div>
          </Card>

          {/* Pros/Cons */}
          <Card>
            <SectionLabel>Formula Comparison</SectionLabel>
            {Object.entries(FORMULAS).map(([k, f]) => (
              <div key={k} style={{ marginBottom: 10, padding: "8px 10px", borderRadius: 3, background: formula === k ? "#f0f4ff" : CREAM, border: `1px solid ${formula === k ? BLUE : MID}` }}>
                <div style={{ fontSize: 10, fontWeight: 700, color: formula === k ? BLUE : STEEL, marginBottom: 3 }}>{f.label}</div>
                <div style={{ fontSize: 10, color: STEEL, lineHeight: 1.5 }}>{f.desc}</div>
              </div>
            ))}
          </Card>
        </div>

        {/* COL 2 */}
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          <Card>
            <SectionLabel>Role Pool Splits</SectionLabel>
            <div style={{ fontSize: 10, color: STEEL, marginBottom: 8 }}>% of distributable pool. BD Override + DD are fixed off the top.</div>
            {ROLES.map(role => (
              <SliderRow key={role.id} label={role.label} value={shares[role.id]} onChange={v => setShares(p => ({ ...p, [role.id]: v }))} min={0} max={70} step={5} color={NAVY} />
            ))}
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: 11, marginTop: 4, padding: "5px 8px", background: sharesTotal === 100 ? GREEN_LIGHT : RED_LIGHT, borderRadius: 3 }}>
              <span>Total</span>
              <span style={{ fontWeight: 700, color: sharesTotal === 100 ? GREEN : RED }}>{sharesTotal}% {sharesTotal !== 100 && "⚠ must = 100%"}</span>
            </div>
          </Card>

          <Card>
            <SectionLabel>KPI Scores — Edit by Role</SectionLabel>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 5, marginBottom: 10 }}>
              {ROLES.map(role => (
                <button key={role.id} onClick={() => setActiveRole(role.id)} style={{
                  padding: "3px 9px", borderRadius: 3, fontSize: 10, fontWeight: 700,
                  cursor: "pointer", border: "none",
                  background: activeRole === role.id ? NAVY : "white",
                  color: activeRole === role.id ? GOLD : STEEL,
                  boxShadow: activeRole === role.id ? "none" : `0 0 0 1px ${MID}`
                }}>{role.label.split(" ")[0]}</button>
              ))}
            </div>
            <div style={{ fontSize: 11, fontWeight: 600, color: NAVY, marginBottom: 8 }}>
              {ROLES.find(r => r.id === activeRole)?.label}
            </div>
            {KPI_CATS.map(cat => (
              <SliderRow key={cat.id}
                label={cat.label}
                value={Math.round((kpiScores[activeRole]?.[cat.id] || 0) * 100)}
                onChange={v => setKpiScores(p => ({ ...p, [activeRole]: { ...p[activeRole], [cat.id]: v / 100 } }))}
                min={0} max={120} step={5} color={cat.color}
                note={cat.kpis.slice(0, 2).join(" · ")}
              />
            ))}
            {(() => {
              const s = kpiScores[activeRole];
              const comp = s ? s.leasing * catWeights.leasing + s.bd * catWeights.bd + s.compliance * catWeights.compliance : 0;
              const compPct = Math.round(comp * 100);
              return (
                <div style={{ marginTop: 8, padding: "7px 10px", borderRadius: 3, background: getScoreBg(comp), display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                  <span style={{ fontSize: 11, fontWeight: 600 }}>Composite KPI</span>
                  <span style={{ fontSize: 16, fontWeight: 800, color: getScoreColor(comp) }}>{compPct}%</span>
                </div>
              );
            })()}
          </Card>

          <Card>
            <SectionLabel>KPI Categories Detail</SectionLabel>
            {KPI_CATS.map(cat => (
              <div key={cat.id} style={{ marginBottom: 12 }}>
                <div style={{ fontSize: 11, fontWeight: 700, color: cat.color, marginBottom: 4, display: "flex", justifyContent: "space-between" }}>
                  <span>{cat.label}</span>
                  <span>{Math.round(catWeights[cat.id] * 100)}% weight</span>
                </div>
                {cat.kpis.map(kpi => (
                  <div key={kpi} style={{ fontSize: 10.5, color: STEEL, padding: "2px 0 2px 10px", borderLeft: `2px solid ${cat.color}40`, lineHeight: 1.5 }}>{kpi}</div>
                ))}
              </div>
            ))}
          </Card>
        </div>

        {/* COL 3 — Results */}
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          <Card>
            <SectionLabel color={GREEN}>Quarterly Payouts</SectionLabel>
            {results.map(r => {
              const compPct = Math.round(r.compositeScore * 100);
              const maxBar = remainingPool * 0.5;
              const barW = Math.min(r.payout / maxBar * 100, 100);
              return (
                <div key={r.id} style={{ marginBottom: 14, paddingBottom: 14, borderBottom: `1px solid ${MID}` }}>
                  <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 4 }}>
                    <span style={{ fontSize: 11.5, fontWeight: 600 }}>{r.label}</span>
                    <span style={{ fontSize: 14, fontWeight: 800, color: NAVY }}>{fmt(r.payout)}</span>
                  </div>
                  <div style={{ display: "flex", gap: 5, marginBottom: 6 }}>
                    <span style={{ fontSize: 9, fontWeight: 700, padding: "2px 5px", borderRadius: 2, background: MID, color: STEEL }}>Pool: {shares[r.id]}%</span>
                    <span style={{ fontSize: 9, fontWeight: 700, padding: "2px 5px", borderRadius: 2, background: getScoreBg(r.compositeScore), color: getScoreColor(r.compositeScore) }}>KPI: {compPct}%</span>
                    {formula === "C" && r.compositeScore >= 1.0 && (
                      <span style={{ fontSize: 9, fontWeight: 700, padding: "2px 5px", borderRadius: 2, background: AMBER_LIGHT, color: AMBER }}>Excess → year-end</span>
                    )}
                    {formula === "C" && r.compositeScore < 0.7 && (
                      <span style={{ fontSize: 9, fontWeight: 700, padding: "2px 5px", borderRadius: 2, background: RED_LIGHT, color: RED }}>Below gate</span>
                    )}
                  </div>
                  <div style={{ background: MID, borderRadius: 2, height: 5, overflow: "hidden" }}>
                    <div style={{ height: "100%", borderRadius: 2, width: barW + "%", background: getScoreColor(r.compositeScore), transition: "width 0.3s" }} />
                  </div>
                </div>
              );
            })}

            <div style={{ padding: "9px 12px", background: RED_LIGHT, borderRadius: 3, marginBottom: 8 }}>
              <div style={{ display: "flex", justifyContent: "space-between" }}>
                <span style={{ fontSize: 11, fontWeight: 600, color: RED }}>BD Override (10% — fixed)</span>
                <span style={{ fontSize: 14, fontWeight: 800, color: RED }}>{fmt(bdOverride)}</span>
              </div>
              <div style={{ fontSize: 9.5, color: STEEL, marginTop: 2 }}>Off the top · not KPI-gated · applies all deals from BD markets</div>
            </div>

            <div style={{ padding: "9px 12px", background: NAVY, borderRadius: 3, marginBottom: 8 }}>
              <div style={{ display: "flex", justifyContent: "space-between" }}>
                <span style={{ fontSize: 11, fontWeight: 600, color: "rgba(255,255,255,0.65)" }}>Deputy Director (25% — fixed)</span>
                <span style={{ fontSize: 14, fontWeight: 800, color: GOLD }}>{fmt(ddShare)}</span>
              </div>
            </div>

            <div style={{ padding: "9px 12px", background: "#f0f4ff", borderRadius: 3, border: `1px solid ${MID}` }}>
              <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 4 }}>
                <span style={{ fontSize: 11, fontWeight: 600, color: NAVY }}>Total distributed</span>
                <span style={{ fontSize: 14, fontWeight: 800, color: NAVY }}>{fmt(results.reduce((s, r) => s + r.payout, 0) + bdOverride + ddShare)}</span>
              </div>
              <div style={{ display: "flex", justifyContent: "space-between" }}>
                <span style={{ fontSize: 10, color: STEEL }}>of gross quarterly pool</span>
                <span style={{ fontSize: 10, fontWeight: 700, color: STEEL }}>{fmt(quarterlyPool)}</span>
              </div>
            </div>
          </Card>

          <Card style={{ background: GREEN_LIGHT, border: `1px solid #c5ddd1` }}>
            <SectionLabel color={GREEN}>Implementation Timeline</SectionLabel>
            {[
              ["Now → Q4 2026", "Design & internal alignment. Calculator used to finalise splits and formula choice."],
              ["Q1 2027", "Go-live for new hires. Existing team grandfathered on current terms."],
              ["Q2 2027", "Full team transitions. Year-end KPI pool replaces Leasing Team Pool."],
              ["Annual", "Formula upgraded (A → B → C) as Monday.com data matures."],
            ].map(([timing, desc]) => (
              <div key={timing} style={{ display: "flex", gap: 10, marginBottom: 10, paddingBottom: 10, borderBottom: `1px solid #c5ddd1` }}>
                <div style={{ fontSize: 10, fontWeight: 700, color: GREEN, minWidth: 90, paddingTop: 1 }}>{timing}</div>
                <div style={{ fontSize: 10.5, color: NAVY, lineHeight: 1.55 }}>{desc}</div>
              </div>
            ))}
            <div style={{ fontSize: 10, color: STEEL, lineHeight: 1.6 }}>
              <strong>Leasing team:</strong> Not eligible for company bonus. Override + year-end KPI pool is the upside equivalent.<br />
              <strong>Pro-rating:</strong> By days worked in quarter (quarterly) and calendar year (year-end pool).
            </div>
          </Card>

          {formula === "C" && (
            <Card style={{ background: AMBER_LIGHT, border: `1px solid #D4A84B` }}>
              <div style={{ fontSize: 10, fontWeight: 700, color: AMBER, marginBottom: 5 }}>Option C — Exceedance Note</div>
              <div style={{ fontSize: 10.5, color: NAVY, lineHeight: 1.6 }}>KPI scores above 100% do not pay out quarterly. Excess rolls to the year-end bonus pool, distributed at Director's discretion. Prevents gaming quarterly targets while preserving upside for sustained performers.</div>
            </Card>
          )}
        </div>
      </div>

      <div style={{ marginTop: 18, paddingTop: 10, borderTop: `1px solid ${MID}`, fontSize: 9.5, color: STEEL, display: "flex", justifyContent: "space-between" }}>
        <span>CORE5 Vietnam (Indochina Kajima) · Internal Design Tool · Not for distribution</span>
        <span>Commission KPI Calculator · v1 · 2026</span>
      </div>
    </div>
  );
}