// BEFORE vs AFTER, split-screen comparison

const COMPARISONS = [
  {
    deal: "No deal · beat got used",
    before: {
      fee: "$0",
      pub: "Never discussed",
      master: "Never discussed",
      paper: "Nothing in writing",
      cred: "Untagged on upload",
      out: "Song streams. You don't see anything, ever. No paper, no proof, no leverage.",
    },
    after: {
      fee: "$0 (still nothing upfront)",
      pub: "Splits documented for yourself",
      master: "Documented for yourself",
      paper: "Receipts kept · session files saved",
      cred: "Register with PRO once streams justify it",
      out: "When the record breaks you walk in with documentation and collect retroactively. The story isn't 'I made that', it's evidence.",
      gross1Yr: 800,
    },
  },
  {
    deal: "Indie · no distro",
    before: {
      fee: "$50 Venmo",
      pub: "0%",
      master: "0%",
      paper: "DM screenshot",
      cred: "Untagged",
      out: "Beat used. Money stops there.",
    },
    after: {
      fee: "$300–$800 + use cap",
      pub: "50% writer share documented",
      master: "Discussed for any later distribution",
      paper: "One-page beat agreement signed",
      cred: "PRO registered",
      out: "If sync or a label finds the song later, the paperwork already exists. You're collectible.",
      gross1Yr: 1500,
    },
  },
  {
    deal: "Indie · with distributor",
    before: {
      fee: "$100 PayPal",
      pub: "'We'll figure it out'",
      master: "Not on the distro splits",
      paper: "Nothing in writing",
      cred: "Hopefully tagged",
      out: "Distro pays the artist. You see nothing from streams. Royalties accumulate in someone else's account.",
    },
    after: {
      fee: "$500–$2,500",
      pub: "50% locked",
      master: "5–15% ownership via distro splits",
      paper: "Beat agreement + distro split setup confirmed",
      cred: "PRO + MLC registered",
      out: "Master pays you direct each cycle. Pub flows quarterly. Everything you're owed lands in your account.",
      gross1Yr: 4800,
    },
  },
  {
    deal: "Signed · indie label",
    before: {
      fee: "$0 advance",
      pub: "Label's pub admin auto-registered under artist",
      master: "0–1 points",
      paper: "Loose producer agreement, no lawyer",
      cred: "Hopefully tagged",
      out: "Label collects. Artist gets a check. You get a Spotify For Artists profile picture.",
    },
    after: {
      fee: "$3K–$8K advance",
      pub: "50% writer share · controlled (not assigned)",
      master: "3–5 points",
      paper: "Producer agreement + Schedule A · attorney reviewed",
      cred: "DSP credits + PRO + MLC + SoundExchange",
      out: "Fee upfront. Points pay quarterly. Audit rights baked in. You can verify the math.",
      gross1Yr: 16000,
    },
  },
  {
    deal: "Major label",
    before: {
      fee: "Never paid",
      pub: "?",
      master: "?",
      paper: "Nothing sent",
      cred: "Hopefully tagged",
      out: "Song goes platinum. You complain on Instagram, tag the artist, lose the relationship, and a positive moment becomes negative.",
    },
    after: {
      fee: "$10K–$30K advance",
      pub: "50% locked",
      master: "5+ points",
      paper: "Producer agreement + Schedule A · attorney mandatory",
      cred: "DSP + liner + PRO + MLC + SoundExchange",
      out: "Money upfront. Royalties downstream. Everything papered. The plaque means something because so does the check.",
      gross1Yr: 38000,
    },
  },
];

function BeforeAfter() {
  const [tab, setTab] = React.useState(0);
  const c = COMPARISONS[tab];

  return (
    <section className="section paper rule-top" style={{ borderTop: "1px solid var(--rule-gold)" }}>
      <div className="page">
        <div className="grid-12" style={{ alignItems: "end", marginBottom: 56 }}>
          <div style={{ gridColumn: "span 7" }}>
            <span className="eyebrow">Five situations · two outcomes</span>
            <h2 className="h-section" style={{ marginTop: 16, color: "var(--bg-paper-ink)" }}>
              The deal you walk into,<br/>
              <em style={{ color: "var(--gold-deep)" }}>two</em> different ways.
            </h2>
          </div>
          <div style={{ gridColumn: "9 / span 4" }}>
            <p className="lede">
              Pick the situation closest to yours. See what producers usually walk away with vs. what's actually on the table when you know the playbook.
            </p>
          </div>
        </div>

        {/* Case picker — Liquid Glass segmented control (paper variant) */}
        <div style={{ marginBottom: 4 }}>
          <GlassSegmented
            full
            variant="paper"
            items={COMPARISONS.map((cc, i) => ({
              id: i,
              num: String(i + 1).padStart(2, "0"),
              label: cc.deal,
            }))}
            active={tab}
            onChange={setTab}
            ariaLabel="Deal situation"
          />
        </div>

        {/* Split comparison */}
        <div className="grid-12" style={{ marginTop: 0 }}>
          <Side
            tone="before"
            heading="Before"
            sub="What producers usually get"
            data={c.before}
          />
          <Side
            tone="after"
            heading="After"
            sub="What you should get"
            data={c.after}
          />
        </div>

        {/* Delta callout */}
        <DeltaBar comparison={c} />
      </div>
    </section>
  );
}

// Standalone NetNet section, used in Ch 03 Your Numbers, decoupled from case studies
function NetNetSection({ embedded }) {
  return (
    <section className={`section rule-top${embedded ? " chapter-embedded" : " paper"}`} style={{ borderTop: "1px solid var(--rule-gold)" }}>
      <div className="page">
        {!embedded ? (
          <div className="grid-12" style={{ alignItems: "end", marginBottom: 40 }}>
            <div style={{ gridColumn: "span 7" }}>
              <span className="eyebrow">Net-Net Calculator</span>
              <h2 className="h-section" style={{ marginTop: 16, color: "var(--bg-paper-ink)" }}>
                But what do you<br/>
                <em style={{ color: "var(--gold-deep)" }}>actually</em> take home?
              </h2>
            </div>
            <div style={{ gridColumn: "9 / span 4" }}>
              <p className="lede">
                The number on the contract isn't the number in your account. Layer in collaborators, manager, lawyer, taxes, then look at what's left.
              </p>
            </div>
          </div>
        ) : (
          <div style={{ marginBottom: 32 }}>
            <span className="eyebrow">Free Tool · The Standard</span>
            <h2 className="h-section" style={{ marginTop: 16 }}>
              How much is <em>yours</em>?
            </h2>
          </div>
        )}
        <NetNetCalculator defaultGross={25000} contextLabel="Year 1 from a strong deal" />
      </div>
    </section>
  );
}

function Side({ tone, heading, sub, data }) {
  const isAfter = tone === "after";
  const bg = isAfter ? "rgba(212,166,74,0.12)" : "transparent";
  const accent = isAfter ? "var(--gold-deep)" : "rgba(24,19,12,0.5)";

  return (
    <div style={{
      gridColumn: "span 6",
      padding: "40px 36px 48px",
      background: bg,
      borderRight: !isAfter ? "1px solid rgba(24,19,12,0.18)" : "none",
      borderBottom: "1px solid rgba(24,19,12,0.18)",
      position: "relative",
    }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 28 }}>
        <div>
          <span className="caption">{sub}</span>
          <div style={{ fontFamily: "var(--sans)", fontWeight: 800, fontSize: "clamp(56px, 7vw, 96px)", letterSpacing: "-0.04em", lineHeight: 0.9, color: accent, marginTop: 8 }}>
            {heading}
          </div>
        </div>
        {isAfter && (
          <span style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.16em", color: "var(--gold-deep)", padding: "4px 10px", border: "1px solid var(--gold-deep)" }}>
            THE STANDARD
          </span>
        )}
      </div>

      <dl style={{ margin: 0, display: "flex", flexDirection: "column", gap: 0 }}>
        <BARow label="Producer fee" v={data.fee} highlight={isAfter} />
        <BARow label="Publishing split" v={data.pub} highlight={isAfter} />
        <BARow label="Master royalty" v={data.master} highlight={isAfter} />
        <BARow label="Paperwork" v={data.paper} highlight={isAfter} />
        <BARow label="Credit" v={data.cred} highlight={isAfter} />
      </dl>

      <div style={{ marginTop: 24, padding: "20px 0 0", borderTop: `1px solid ${isAfter ? "rgba(24,19,12,0.4)" : "rgba(24,19,12,0.18)"}` }}>
        <span className="caption">Outcome</span>
        <p className="pull-serif" style={{
          fontSize: "clamp(20px, 2.2vw, 28px)",
          lineHeight: 1.25,
          color: isAfter ? "var(--bg-paper-ink)" : "rgba(24,19,12,0.6)",
          margin: "8px 0 0",
          fontWeight: 400,
        }}>
          {data.out}
        </p>
      </div>
    </div>
  );
}

function BARow({ label, v, highlight }) {
  return (
    <div style={{
      display: "flex",
      justifyContent: "space-between",
      alignItems: "baseline",
      gap: 16,
      padding: "12px 0",
      borderBottom: "1px dashed rgba(24,19,12,0.18)",
    }}>
      <span style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.16em", textTransform: "uppercase", color: "rgba(24,19,12,0.55)" }}>{label}</span>
      <span style={{
        fontFamily: "var(--sans)",
        fontWeight: highlight ? 700 : 500,
        fontSize: 18,
        letterSpacing: "-0.01em",
        textAlign: "right",
        color: highlight ? "var(--bg-paper-ink)" : "rgba(24,19,12,0.6)",
        fontVariantNumeric: "tabular-nums",
      }}>{v}</span>
    </div>
  );
}

function DeltaBar({ comparison }) {
  // Just a flavor "delta" line, show the editorial conclusion
  return (
    <div style={{ display: "grid", gridTemplateColumns: "1fr auto 1fr", alignItems: "center", marginTop: 40, gap: 24 }}>
      <div className="caption" style={{ textAlign: "right" }}>The difference isn't talent.</div>
      <div style={{
        fontFamily: "var(--sans)",
        fontWeight: 800,
        fontSize: "clamp(48px, 6vw, 88px)",
        letterSpacing: "-0.04em",
        color: "var(--gold-deep)",
        lineHeight: 1,
      }}>
        Δ = paperwork
      </div>
      <div className="caption">It's what was written down.</div>
    </div>
  );
}

// ================ NET-NET CALCULATOR ================
// What you actually take home after collaborators, reps, and taxes.

const REPS_CONFIG = [
  { id: "manager",  label: "Manager",          defaultPct: 20, defaultOn: true,  note: "Industry standard 15–20%. Takes their cut off the top of every check." },
  { id: "lawyer",   label: "Music Lawyer",     defaultPct: 5,  defaultOn: true,  note: "5% of the deal, or hourly ($350–$600), or flat per deal. Worth every penny on a major." },
  { id: "bizmgr",   label: "Business Manager", defaultPct: 5,  defaultOn: false, note: "5% to handle accounting, taxes, royalty audits. Worth it once revenue compounds." },
  { id: "prodDeal", label: "Production deal",  defaultPct: 25, defaultOn: false, note: "If you're signed to a production deal, the parent takes 15–50% of your income off the top. Negotiable, but real." },
  { id: "agent",    label: "Agent",            defaultPct: 10, defaultOn: false, note: "10% on bookings / branded / sync agency work. Not always relevant to producers." },
];

// Tax interview data
const TAX_COUNTRIES = [
  { id: "us",    label: "United States",   base: null },
  { id: "ca",    label: "Canada",          base: 32 },
  { id: "uk",    label: "United Kingdom",  base: 32 },
  { id: "au",    label: "Australia",       base: 32 },
  { id: "de",    label: "Germany",         base: 35 },
  { id: "nl",    label: "Netherlands",     base: 36 },
  { id: "other", label: "Other / unsure",  base: 28 },
];
const US_STATES = [
  { id: "TX", label: "Texas, 0% state",       rate: 0 },
  { id: "FL", label: "Florida, 0% state",     rate: 0 },
  { id: "NV", label: "Nevada, 0% state",      rate: 0 },
  { id: "WA", label: "Washington, 0% state",  rate: 0 },
  { id: "TN", label: "Tennessee, 0% state",   rate: 0 },
  { id: "GA", label: "Georgia, ~5.75%",       rate: 5.75 },
  { id: "IL", label: "Illinois, ~4.95%",      rate: 4.95 },
  { id: "NY", label: "New York, ~6.85%",      rate: 6.85 },
  { id: "CA", label: "California, ~9.3%",     rate: 9.3 },
  { id: "NJ", label: "New Jersey, ~8.97%",    rate: 8.97 },
  { id: "OR", label: "Oregon, ~9.9%",         rate: 9.9 },
  { id: "avg", label: "Other state, estimate ~5%", rate: 5 },
];
const TAX_ENTITIES = [
  { id: "soleprop", label: "Sole proprietor · self-employed", mult: 1.00, note: "Default for most producers without an LLC. Pays full self-employment tax (15.3%) + income tax." },
  { id: "llc",      label: "LLC · single-member (default)",   mult: 1.00, note: "Taxed as sole prop unless you elect S-Corp. No liability shield for tax math." },
  { id: "scorp",    label: "S-Corp election",                  mult: 0.85, note: "Reasonable salary + distributions. Cuts SE liability. Common for $80K+/yr." },
  { id: "ccorp",    label: "C-Corp",                            mult: 0.82, note: "Corporate rate (21%) + dividend tax. Rare for individual producers." },
  { id: "employee", label: "W-2 employee (rare)",               mult: 0.78, note: "You receive a W-2, no SE tax. Most producers are 1099." },
];

function computeTaxPct({ country, state, entity }) {
  let base;
  if (country === "us") {
    // Sole prop combined effective: ~22% fed bracket + 15.3% SE × 0.7 deductible portion + ~5% state baseline
    base = 28;
    const st = US_STATES.find((s) => s.id === state);
    if (st) base += st.rate;
  } else {
    base = TAX_COUNTRIES.find((c) => c.id === country)?.base ?? 28;
  }
  const mult = TAX_ENTITIES.find((e) => e.id === entity)?.mult ?? 1;
  return Math.max(0, Math.min(55, Math.round(base * mult)));
}

function getTaxRecommendations({
  taxEnabled, taxCountry, taxState, taxEntity, taxPct, gross, afterReps,
  reps, activeReps, totalRepPct, collaborators,
}) {
  const tips = [];

  if (!taxEnabled) {
    tips.push({
      tone: "neutral",
      text: "Tax is off, the waterfall shows what you keep after collaborators and reps, before estimated tax. Toggle on for a rough bank-deposit number.",
    });
  }

  if (taxEnabled && taxCountry === "us" && taxEntity === "soleprop" && gross >= 80_000) {
    tips.push({
      tone: "gold",
      text: "Past ~$80K/yr as a sole prop, ask a CPA about S-Corp election, reasonable salary + distributions can cut self-employment tax.",
    });
  }

  if (taxEnabled && taxCountry === "us" && ["TX", "FL", "NV", "WA", "TN"].includes(taxState)) {
    tips.push({
      tone: "neutral",
      text: "No state income tax in your selection, you still owe federal income tax and self-employment tax on 1099 income.",
    });
  }

  if (taxEnabled && taxCountry === "us" && ["CA", "NY", "NJ", "OR"].includes(taxState)) {
    tips.push({
      tone: "warn",
      text: "High state rate in your selection, factor state tax into your fee floor; a $25K deal lands lighter than the same deal in TX or FL.",
    });
  }

  if (taxEnabled && taxPct >= 38) {
    tips.push({
      tone: "warn",
      text: "Effective rate is steep for this scenario, home studio, gear, travel, and health insurance can lower taxable income. A CPA beats guessing.",
    });
  }

  if (reps.prodDeal?.active) {
    tips.push({
      tone: "warn",
      text: "Production deal parent takes their % off the top, negotiate what's included (advances, marketing, touring) and what still pays through to you.",
    });
  }

  if (totalRepPct > 22 && reps.manager?.active) {
    tips.push({
      tone: "gold",
      text: "Rep stack is heavy, manager standard is ~20%. Extra points should come with sync, brand, or touring work, not just beat placements.",
    });
  }

  if (!reps.bizmgr?.active && gross >= 100_000) {
    tips.push({
      tone: "gold",
      text: "Past ~$100K/yr, a business manager (≈5%) often pays for itself via royalty audits, quarterly estimates, and catching missing PRO/MLC money.",
    });
  }

  if (collaborators.length > 1) {
    tips.push({
      tone: "neutral",
      text: "Co-producer splits should match a signed agreement before the session, the % here should be paperwork, not a handshake.",
    });
  }

  if (taxEnabled && taxCountry === "us" && taxEntity === "employee") {
    tips.push({
      tone: "neutral",
      text: "W-2 is rare for producers, most are 1099. If you're actually on payroll, self-employment tax doesn't apply; confirm with whoever issues your check.",
    });
  }

  if (taxEnabled && afterReps > 0 && afterReps < 15_000) {
    tips.push({
      tone: "neutral",
      text: "Low take-home after reps, still set aside ~25–30% for tax if you're 1099, even on smaller checks. Quarterly estimates avoid April surprises.",
    });
  }

  return tips.slice(0, 4);
}

const NN_PRESETS = [
  {
    id: "beat",
    label: "Beat Placement",
    gross: 5000,
    sliderMax: 50000,
    collabs: [{ id: 1, role: "Producer", name: "You", share: 100 }],
    reps: { manager: { active: true, pct: 20 }, lawyer: { active: false, pct: 5 }, bizmgr: { active: false, pct: 5 }, prodDeal: { active: false, pct: 25 }, agent: { active: false, pct: 10 } },
  },
  {
    id: "everything",
    label: "Everything",
    gross: 200000,
    sliderMax: 1000000,
    collabs: [
      { id: 1, role: "Producer", name: "You", share: 60 },
      { id: 2, role: "Co-producer", name: "Co-producer", share: 40 },
    ],
    reps: { manager: { active: true, pct: 20 }, lawyer: { active: true, pct: 5 }, bizmgr: { active: true, pct: 5 }, prodDeal: { active: false, pct: 25 }, agent: { active: false, pct: 10 } },
  },
];

function NetNetCalculator({ defaultGross = 25000, contextLabel = "" }) {
  const [gross, setGross] = React.useState(defaultGross);
  const [collaborators, setCollaborators] = React.useState([
    { id: 1, role: "Producer", name: "You", share: 100 },
  ]);
  const [reps, setReps] = React.useState(() =>
    REPS_CONFIG.reduce((acc, r) => ({ ...acc, [r.id]: { active: r.defaultOn, pct: r.defaultPct } }), {})
  );
  const [activePreset, setActivePreset] = React.useState(null);
  const sliderMax = activePreset ? activePreset.sliderMax : 200000;
  const [taxEnabled, setTaxEnabled] = React.useState(false);
  const [taxCountry, setTaxCountry] = React.useState("us");
  const [taxState, setTaxState] = React.useState("avg");
  const [taxEntity, setTaxEntity] = React.useState("soleprop");
  const taxPct = computeTaxPct({ country: taxCountry, state: taxState, entity: taxEntity });

  React.useEffect(() => { setGross(defaultGross); }, [defaultGross]);

  // Math
  const totalCollabShare = collaborators.reduce((a, c) => a + Number(c.share), 0);
  const yourShare = collaborators[0]?.share || 0;
  const yourShareNormalized = totalCollabShare === 0 ? 0 : (yourShare / totalCollabShare);
  const afterCollabs = gross * yourShareNormalized;
  const lostToCollabs = gross - afterCollabs;

  const activeReps = REPS_CONFIG.filter((r) => reps[r.id].active);
  const totalRepPct = activeReps.reduce((a, r) => a + reps[r.id].pct, 0);
  const lostToReps = afterCollabs * (totalRepPct / 100);
  const afterReps = afterCollabs - lostToReps;

  const lostToTax = taxEnabled ? afterReps * (taxPct / 100) : 0;
  const netNet = afterReps - lostToTax;
  const takeHomePct = gross > 0 ? (netNet / gross) * 100 : 0;

  const recommendations = getTaxRecommendations({
    taxEnabled,
    taxCountry,
    taxState,
    taxEntity,
    taxPct,
    gross,
    afterReps,
    reps,
    activeReps,
    totalRepPct,
    collaborators,
  });

  const applyPreset = (p) => {
    setActivePreset(p);
    setGross(p.gross);
    setCollaborators(p.collabs);
    setReps(p.reps);
  };

  const updateCollab = (id, patch) => setCollaborators((cs) => cs.map((c) => (c.id === id ? { ...c, ...patch } : c)));
  const addCollab = (role) => {
    const newId = Math.max(...collaborators.map((c) => c.id), 0) + 1;
    setCollaborators((cs) => {
      // Auto-divide evenly across all collaborators (you + everyone else)
      const next = [...cs, { id: newId, role, name: role === "Manager" ? "Manager" : role === "Lawyer" ? "Lawyer" : role, share: 0 }];
      const even = +(100 / next.length).toFixed(1);
      return next.map((c) => ({ ...c, share: even }));
    });
  };
  const removeCollab = (id) => setCollaborators((cs) => {
    if (cs.length <= 1) return cs;
    const next = cs.filter((c) => c.id !== id);
    // Redistribute evenly after removal
    const even = +(100 / next.length).toFixed(1);
    return next.map((c) => ({ ...c, share: even }));
  });
  const splitEvenly = () => setCollaborators((cs) => {
    const even = +(100 / cs.length).toFixed(1);
    return cs.map((c) => ({ ...c, share: even }));
  });
  const setRep = (id, patch) => setReps((r) => ({ ...r, [id]: { ...r[id], ...patch } }));

  return (
    <div style={{
      marginTop: 24,
      background: "var(--bg-paper-ink)",
      color: "var(--bg-paper)",
      padding: "40px 36px 48px",
      position: "relative",
    }}>
      {/* Header */}
      <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 24, flexWrap: "wrap", gap: 12 }}>
        <h3 style={{ fontFamily: "var(--sans)", fontWeight: 800, fontSize: "clamp(22px, 3vw, 36px)", letterSpacing: "-0.03em", lineHeight: 1, margin: 0, color: "var(--bg-paper)" }}>
          Set the gross. Stack the cuts. <em style={{ fontFamily: "var(--serif)", fontWeight: 400, fontStyle: "italic", color: "var(--gold)" }}>Read what's left.</em>
        </h3>
        <span style={{ fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.16em", color: "var(--gold)", textTransform: "uppercase", whiteSpace: "nowrap" }}>◆ The Waterfall</span>
      </div>

      {/* Preset selector */}
      <div style={{ display: "flex", gap: 8, marginBottom: 20, flexWrap: "wrap" }}>
        {NN_PRESETS.map((p) => {
          const isActive = activePreset && activePreset.id === p.id;
          return (
            <button
              key={p.id}
              type="button"
              onClick={() => applyPreset(p)}
              style={{
                fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.14em", textTransform: "uppercase",
                padding: "8px 14px", cursor: "pointer", transition: "all 0.15s ease",
                background: isActive ? "rgba(212,166,74,0.12)" : "rgba(243,236,224,0.05)",
                border: `1px solid ${isActive ? "var(--gold)" : "rgba(243,236,224,0.18)"}`,
                color: isActive ? "var(--gold)" : "rgba(243,236,224,0.65)",
              }}
            >
              {p.label}
            </button>
          );
        })}
      </div>

      <div className="tool-split" style={{ gap: 0, border: "1px solid rgba(243,236,224,0.12)" }}>
        {/* LEFT: Inputs */}
        <div style={{ display: "flex", flexDirection: "column", gap: 28, borderRight: "1px solid rgba(243,236,224,0.12)", padding: "clamp(22px, 3vw, 32px)" }}>
          {/* Gross deal value */}
          <Block label="01 · Gross deal value" sub="Total before any cut">
            <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 12, gap: 12 }}>
              <span className="dk-caption">DRAG OR TYPE</span>
              <div style={{ display: "flex", alignItems: "baseline", gap: 4 }}>
                <span style={{ fontFamily: "var(--sans)", fontWeight: 800, fontSize: "clamp(20px, 2.4vw, 28px)", color: "var(--gold)" }}>$</span>
                <input
                  type="number"
                  value={gross}
                  min={0}
                  step={500}
                  onChange={(e) => setGross(Math.max(0, Number(e.target.value) || 0))}
                  style={{
                    background: "transparent", border: "none", borderBottom: "1px solid rgba(212,166,74,0.4)",
                    color: "var(--gold)", fontFamily: "var(--sans)", fontWeight: 800,
                    fontSize: "clamp(28px, 3.4vw, 44px)", letterSpacing: "-0.025em",
                    fontVariantNumeric: "tabular-nums", textAlign: "right", width: 180,
                    outline: "none", padding: "2px 4px",
                  }}
                />
              </div>
            </div>
            <input
              type="range"
              min="0"
              max={sliderMax}
              step={sliderMax >= 500000 ? 5000 : 500}
              value={gross}
              onChange={(e) => setGross(Number(e.target.value))}
              className="pu-slider"
              style={{ width: "100%", "--pu-pct": `${(gross / sliderMax) * 100}%` }}
            />
            <div style={{ display: "flex", justifyContent: "space-between", marginTop: 6 }} className="dk-caption">
              <span>$0</span>
              <span>${sliderMax >= 500000 ? "250K" : sliderMax === 50000 ? "12.5K" : "50K"}</span>
              <span>${sliderMax >= 500000 ? "500K" : sliderMax === 50000 ? "25K" : "100K"}</span>
              <span>${sliderMax >= 500000 ? "1M" : sliderMax === 50000 ? "50K" : "200K"}</span>
            </div>
          </Block>

          {/* Collaborators */}
          <Block label="02 · Collaborators on the producer side" sub="Co-producers and songwriters who share your slice">
            <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              {collaborators.map((c, i) => (
                <NetCollabRow
                  key={c.id}
                  c={c}
                  isYou={i === 0}
                  onChange={(patch) => updateCollab(c.id, patch)}
                  onRemove={() => removeCollab(c.id)}
                />
              ))}
            </div>
            <div style={{ display: "flex", gap: 8, marginTop: 12, flexWrap: "wrap" }}>
              <DkAddBtn label="+ Co-producer" onClick={() => addCollab("Co-producer")} />
              <DkAddBtn label="+ Songwriter" onClick={() => addCollab("Songwriter")} />
              <DkAddBtn label="+ Engineer" onClick={() => addCollab("Engineer")} />
              <DkAddBtn label="↺ Split evenly" onClick={splitEvenly} />
            </div>
          </Block>

          {/* Reps */}
          <Block label="03 · Representation" sub="Manager, lawyer, biz manager, each off the top">
            <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              {REPS_CONFIG.map((r) => (
                <NetRepRow
                  key={r.id}
                  r={r}
                  state={reps[r.id]}
                  onToggle={() => setRep(r.id, { active: !reps[r.id].active })}
                  onPctChange={(pct) => setRep(r.id, { pct })}
                />
              ))}
            </div>
          </Block>

          {/* Tax, optional */}
          <Block label="04 · Tax estimate" sub={taxEnabled ? "On · rough effective rate" : "Off · pre-tax waterfall"}>
            <TaxToggleRow
              enabled={taxEnabled}
              onToggle={() => setTaxEnabled((v) => !v)}
              taxPct={taxPct}
            />
            {taxEnabled && (
              <TaxInterview
                country={taxCountry} setCountry={setTaxCountry}
                state={taxState} setState={setTaxState}
                entity={taxEntity} setEntity={setTaxEntity}
                taxPct={taxPct}
              />
            )}
          </Block>

          <TaxRecommendations items={recommendations} />
        </div>

        {/* RIGHT: Waterfall */}
        <div style={{ position: "sticky", top: 24, padding: "clamp(22px, 3vw, 32px)" }}>
          <div style={{ padding: "32px 32px 40px", background: "rgba(212,166,74,0.06)", border: "1px solid rgba(212,166,74,0.4)" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 20 }}>
              <span style={{ fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.18em", color: "var(--gold)" }}>THE WATERFALL</span>
              <span className="dk-caption">RUNNING BALANCE</span>
            </div>

            <Waterfall steps={[
              { label: "Gross deal value", amt: gross, sub: contextLabel || "Your scenario", tone: "start" },
              { label: `Collaborators take${collaborators.length > 1 ? ` (${collaborators.length - 1})` : ""}`, amt: -lostToCollabs, sub: collaborators.length > 1 ? collaborators.slice(1).map((c) => `${c.name} ${c.share}%`).join(" · ") : "Just you, no split", tone: "cut" },
              ...activeReps.map((r) => ({
                label: `${r.label} (${reps[r.id].pct}%)`,
                amt: -(afterCollabs * (reps[r.id].pct / 100)),
                sub: r.note,
                tone: "cut",
              })),
              ...(taxEnabled ? [{
                label: `Tax (${taxPct}%)`,
                amt: -lostToTax,
                sub: "Rough effective rate, not your actual return",
                tone: "cut",
              }] : []),
              {
                label: taxEnabled ? "Net-Net to you" : "Pre-tax to you",
                amt: netNet,
                sub: taxEnabled
                  ? `${takeHomePct.toFixed(0)}% of gross, estimated after tax`
                  : `${takeHomePct.toFixed(0)}% of gross before tax (toggle tax for bank estimate)`,
                tone: "end",
              },
            ]} max={gross} />

            <div style={{ marginTop: 24, paddingTop: 24, borderTop: "1px solid rgba(212,166,74,0.3)", display: "flex", justifyContent: "space-between", alignItems: "baseline", flexWrap: "wrap", gap: 12 }}>
              <div>
                <span className="dk-caption">{taxEnabled ? "YOU KEEP (EST. AFTER TAX)" : "YOU KEEP (PRE-TAX)"}</span>
                <div style={{ display: "flex", alignItems: "baseline", gap: 8 }}>
                  <span style={{ fontFamily: "var(--sans)", fontWeight: 800, fontSize: "clamp(40px, 5vw, 64px)", letterSpacing: "-0.035em", color: "var(--gold)", lineHeight: 1, fontVariantNumeric: "tabular-nums" }}>
                    ${formatNum(netNet)}
                  </span>
                </div>
                <p style={{ fontFamily: "var(--serif)", fontStyle: "italic", fontSize: 14, color: "rgba(243,236,224,0.7)", margin: "6px 0 0" }}>
                  out of ${formatNum(gross)} on the deal sheet
                </p>
              </div>
              <div style={{ textAlign: "right" }}>
                <span className="dk-caption">EFFECTIVE TAKE-HOME</span>
                <div style={{ fontFamily: "var(--sans)", fontWeight: 700, fontSize: 32, color: takeHomePct >= 60 ? "#8acaa0" : takeHomePct >= 40 ? "var(--gold)" : "#e88a7d", letterSpacing: "-0.02em", fontVariantNumeric: "tabular-nums" }}>
                  {takeHomePct.toFixed(0)}%
                </div>
              </div>
            </div>
          </div>

          <p style={{ fontFamily: "var(--serif)", fontStyle: "italic", fontSize: 15, color: "rgba(243,236,224,0.6)", marginTop: 16, lineHeight: 1.4 }}>
            ★ This is why a $20K "deal" can be a $9K paycheck. The number on the contract is not the number in your account.
          </p>
        </div>
      </div>
    </div>
  );
}

function Block({ label, sub, children }) {
  return (
    <div style={{ padding: "20px 22px", background: "rgba(243,236,224,0.04)", border: "1px solid rgba(243,236,224,0.12)" }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 14, flexWrap: "wrap", gap: 8 }}>
        <span style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.16em", color: "var(--gold)", textTransform: "uppercase" }}>{label}</span>
        <span className="dk-caption">{sub}</span>
      </div>
      {children}
    </div>
  );
}

function NetCollabRow({ c, isYou, onChange, onRemove }) {
  const accent = isYou ? "var(--gold)" : "rgba(243,236,224,0.6)";
  return (
    <div style={{ display: "grid", gridTemplateColumns: "auto 1fr auto auto auto", gap: 10, alignItems: "center", padding: "8px 10px", background: "rgba(0,0,0,0.18)", border: "1px solid rgba(243,236,224,0.08)" }}>
      <span style={{ fontFamily: "var(--mono)", fontSize: 9, letterSpacing: "0.14em", color: accent, padding: "3px 6px", border: `1px solid ${accent}`, fontWeight: 600 }}>
        {c.role.toUpperCase()}
      </span>
      <input
        value={c.name}
        disabled={isYou}
        onChange={(e) => onChange({ name: e.target.value })}
        style={{
          background: "transparent",
          border: "none",
          color: "var(--bg-paper)",
          fontFamily: "var(--sans)",
          fontWeight: 600,
          fontSize: 14,
          padding: "4px 0",
          outline: "none",
          width: "100%",
          letterSpacing: "-0.01em",
        }}
      />
      <input
        type="range"
        min="0"
        max="100"
        step="0.5"
        value={c.share}
        onChange={(e) => onChange({ share: Number(e.target.value) })}
        className="pu-slider"
        style={{ width: 90, "--pu-pct": `${c.share}%` }}
      />
      <div style={{ display: "flex", alignItems: "baseline", gap: 2 }}>
        <input
          type="number"
          value={c.share}
          min="0"
          max="100"
          step="0.5"
          onChange={(e) => onChange({ share: Math.max(0, Math.min(100, Number(e.target.value) || 0)) })}
          style={{
            background: "transparent",
            border: "none",
            borderBottom: `1px solid ${accent}`,
            color: accent,
            fontFamily: "var(--sans)",
            fontWeight: 700,
            fontSize: 14,
            width: 40,
            textAlign: "right",
            padding: "2px 2px",
            outline: "none",
            fontVariantNumeric: "tabular-nums",
          }}
        />
        <span style={{ color: accent, fontFamily: "var(--sans)", fontWeight: 700, fontSize: 14 }}>%</span>
      </div>
      {isYou ? <span style={{ width: 24 }}></span> : (
        <button onClick={onRemove} style={{ background: "transparent", border: "1px solid rgba(243,236,224,0.18)", color: "rgba(243,236,224,0.5)", fontFamily: "var(--mono)", fontSize: 12, width: 24, height: 24, cursor: "pointer" }}>×</button>
      )}
    </div>
  );
}

function TaxToggleRow({ enabled, onToggle, taxPct }) {
  return (
    <div style={{
      display: "flex",
      alignItems: "center",
      justifyContent: "space-between",
      gap: 16,
      padding: "12px 14px",
      marginBottom: enabled ? 16 : 0,
      background: enabled ? "rgba(212,166,74,0.08)" : "rgba(0,0,0,0.15)",
      border: `1px solid ${enabled ? "rgba(212,166,74,0.4)" : "rgba(243,236,224,0.1)"}`,
      transition: "all 0.18s ease",
    }}>
      <div style={{ flex: 1 }}>
        <div style={{ fontFamily: "var(--sans)", fontWeight: 600, fontSize: 14, color: enabled ? "var(--bg-paper)" : "rgba(243,236,224,0.55)" }}>
          Include estimated tax
        </div>
        <div className="dk-caption" style={{ marginTop: 4, color: "rgba(243,236,224,0.45)" }}>
          {enabled ? "Waterfall deducts a rough effective rate" : "See take-home after collabs & reps only"}
        </div>
      </div>
      {enabled && (
        <div style={{ display: "flex", alignItems: "baseline", gap: 2, marginRight: 8 }}>
          <span style={{ fontFamily: "var(--sans)", fontWeight: 800, fontSize: 22, color: "var(--gold)", fontVariantNumeric: "tabular-nums" }}>{taxPct}</span>
          <span style={{ fontFamily: "var(--sans)", fontWeight: 600, fontSize: 14, color: "rgba(243,236,224,0.5)" }}>%</span>
        </div>
      )}
      <button type="button" onClick={onToggle} aria-pressed={enabled} style={{
        width: 44, height: 24, flexShrink: 0,
        background: enabled ? "var(--gold)" : "rgba(243,236,224,0.15)",
        border: "none", position: "relative", cursor: "pointer", padding: 0,
        transition: "background 0.2s ease",
      }}>
        <span style={{
          position: "absolute", top: 3, left: enabled ? 23 : 3,
          width: 18, height: 18,
          background: enabled ? "#16110a" : "var(--bg-paper)",
          transition: "left 0.2s ease",
        }} />
      </button>
    </div>
  );
}

function TaxRecommendations({ items }) {
  if (!items.length) return null;
  const toneColor = (tone) => (
    tone === "gold" ? "var(--gold)" : tone === "warn" ? "#e8a87c" : "rgba(243,236,224,0.65)"
  );
  return (
    <div style={{
      padding: "18px 20px",
      background: "rgba(212,166,74,0.05)",
      border: "1px solid rgba(212,166,74,0.25)",
    }}>
      <span style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.16em", color: "var(--gold)", textTransform: "uppercase" }}>
        Recommendations
      </span>
      <ul style={{ listStyle: "none", padding: 0, margin: "12px 0 0", display: "flex", flexDirection: "column", gap: 10 }}>
        {items.map((item, i) => (
          <li key={i} style={{ display: "flex", gap: 12, alignItems: "flex-start" }}>
            <span style={{ fontFamily: "var(--mono)", fontSize: 10, color: toneColor(item.tone), minWidth: 18, paddingTop: 2 }}>
              {item.tone === "warn" ? "!" : item.tone === "gold" ? "★" : "→"}
            </span>
            <span style={{ fontFamily: "var(--sans)", fontSize: 13, lineHeight: 1.45, color: "rgba(243,236,224,0.78)" }}>
              {item.text}
            </span>
          </li>
        ))}
      </ul>
    </div>
  );
}

// ---- Tax interview ----
function TaxInterview({ country, setCountry, state, setState, entity, setEntity, taxPct }) {
  const isUS = country === "us";
  const entityObj = TAX_ENTITIES.find((e) => e.id === entity);
  const stateObj = US_STATES.find((s) => s.id === state);
  return (
    <div>
      {/* Top row: rate readout */}
      <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 16, paddingBottom: 14, borderBottom: "1px solid rgba(243,236,224,0.1)" }}>
        <span className="dk-caption">ESTIMATED EFFECTIVE RATE</span>
        <div style={{ display: "flex", alignItems: "baseline", gap: 4 }}>
          <span style={{ fontFamily: "var(--sans)", fontWeight: 800, fontSize: 32, letterSpacing: "-0.025em", color: "var(--gold)", fontVariantNumeric: "tabular-nums" }}>{taxPct}</span>
          <span style={{ fontFamily: "var(--sans)", fontWeight: 700, fontSize: 18, color: "rgba(243,236,224,0.6)" }}>%</span>
        </div>
      </div>

      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        <TaxQ label="Where do you live?">
          <TaxSelect value={country} onChange={setCountry} options={TAX_COUNTRIES} />
        </TaxQ>

        {isUS && (
          <TaxQ label="Which state?">
            <TaxSelect value={state} onChange={setState} options={US_STATES} />
          </TaxQ>
        )}

        <TaxQ label="Business entity?" hint={entityObj?.note}>
          <TaxSelect value={entity} onChange={setEntity} options={TAX_ENTITIES} />
        </TaxQ>
      </div>

      <p style={{
        marginTop: 16,
        padding: "10px 12px",
        fontFamily: "var(--mono)",
        fontSize: 10,
        lineHeight: 1.5,
        letterSpacing: "0.04em",
        color: "rgba(243,236,224,0.55)",
        background: "rgba(192,57,43,0.08)",
        border: "1px solid rgba(192,57,43,0.3)",
      }}>
        ⚠ NOT FINANCIAL ADVICE, ROUGH ESTIMATE BASED ON COUNTRY, STATE, AND ENTITY ASSUMPTIONS AT AVERAGE EARNINGS. ACTUAL RATE DEPENDS ON DEDUCTIONS, BRACKETS, AND YOUR CPA. CONSULT ONE.
      </p>
    </div>
  );
}

function TaxQ({ label, hint, children }) {
  return (
    <div>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 6, gap: 8 }}>
        <span style={{ fontFamily: "var(--sans)", fontWeight: 600, fontSize: 13, color: "var(--bg-paper)" }}>{label}</span>
        {hint && <span style={{ fontFamily: "var(--mono)", fontSize: 9, letterSpacing: "0.06em", color: "rgba(243,236,224,0.5)", textAlign: "right", maxWidth: "60%", lineHeight: 1.35 }}>{hint}</span>}
      </div>
      {children}
    </div>
  );
}

function TaxSelect({ value, onChange, options }) {
  return (
    <div style={{ position: "relative" }}>
      <select
        value={value}
        onChange={(e) => onChange(e.target.value)}
        style={{
          width: "100%",
          background: "rgba(0,0,0,0.25)",
          color: "var(--bg-paper)",
          border: "1px solid rgba(243,236,224,0.18)",
          fontFamily: "var(--sans)",
          fontWeight: 600,
          fontSize: 14,
          padding: "10px 12px",
          appearance: "none",
          cursor: "pointer",
          letterSpacing: "-0.01em",
        }}
      >
        {options.map((o) => (
          <option key={o.id} value={o.id} style={{ background: "#16110a", color: "var(--bg-paper)" }}>
            {o.label}
          </option>
        ))}
      </select>
      <span style={{ position: "absolute", right: 12, top: "50%", transform: "translateY(-50%)", pointerEvents: "none", color: "var(--gold)", fontSize: 11 }}>▾</span>
    </div>
  );
}

function NetRepRow({ r, state, onToggle, onPctChange }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "auto 1fr auto auto", gap: 12, alignItems: "center", padding: "10px 12px", background: state.active ? "rgba(212,166,74,0.06)" : "rgba(0,0,0,0.15)", border: `1px solid ${state.active ? "rgba(212,166,74,0.4)" : "rgba(243,236,224,0.08)"}`, transition: "all 0.18s ease" }}>
      <button onClick={onToggle} style={{
        width: 36, height: 20,
        background: state.active ? "var(--gold)" : "rgba(243,236,224,0.15)",
        border: "none",
        position: "relative",
        cursor: "pointer",
        padding: 0,
        transition: "background 0.2s ease",
      }}>
        <span style={{
          position: "absolute",
          top: 2,
          left: state.active ? 18 : 2,
          width: 16, height: 16,
          background: state.active ? "#16110a" : "var(--bg-paper)",
          transition: "left 0.2s ease",
        }}></span>
      </button>
      <div>
        <div style={{ fontFamily: "var(--sans)", fontWeight: 600, fontSize: 14, color: state.active ? "var(--bg-paper)" : "rgba(243,236,224,0.4)" }}>
          {r.label}
        </div>
        <div className="dk-caption" style={{ marginTop: 2, color: "rgba(243,236,224,0.45)" }}>{r.note}</div>
      </div>
      <input
        type="range"
        min="0"
        max="50"
        step="0.5"
        value={state.pct}
        disabled={!state.active}
        onChange={(e) => onPctChange(Number(e.target.value))}
        className="pu-slider"
        style={{ width: 100, "--pu-pct": `${(state.pct / 50) * 100}%`, opacity: state.active ? 1 : 0.3 }}
      />
      <div style={{ display: "flex", alignItems: "baseline", gap: 2, minWidth: 56, justifyContent: "flex-end" }}>
        <input
          type="number"
          value={state.pct}
          min="0"
          max="50"
          step="0.5"
          disabled={!state.active}
          onChange={(e) => onPctChange(Math.max(0, Math.min(50, Number(e.target.value) || 0)))}
          style={{
            background: "transparent",
            border: "none",
            borderBottom: `1px solid ${state.active ? "var(--gold)" : "rgba(243,236,224,0.18)"}`,
            color: state.active ? "var(--gold)" : "rgba(243,236,224,0.3)",
            fontFamily: "var(--sans)",
            fontWeight: 700,
            fontSize: 16,
            width: 38,
            textAlign: "right",
            padding: "2px 2px",
            outline: "none",
            fontVariantNumeric: "tabular-nums",
            opacity: state.active ? 1 : 0.5,
          }}
        />
        <span style={{ fontFamily: "var(--sans)", fontWeight: 700, fontSize: 16, color: state.active ? "var(--gold)" : "rgba(243,236,224,0.3)" }}>%</span>
      </div>
    </div>
  );
}

function DkAddBtn({ label, onClick }) {
  return (
    <button onClick={onClick} style={{
      background: "transparent",
      border: "1px dashed rgba(243,236,224,0.25)",
      color: "rgba(243,236,224,0.7)",
      fontFamily: "var(--mono)",
      fontSize: 10,
      letterSpacing: "0.14em",
      padding: "6px 10px",
      cursor: "pointer",
      textTransform: "uppercase",
      transition: "all 0.18s ease",
    }}
    onMouseEnter={(e) => { e.currentTarget.style.borderColor = "var(--gold)"; e.currentTarget.style.color = "var(--gold)"; }}
    onMouseLeave={(e) => { e.currentTarget.style.borderColor = "rgba(243,236,224,0.25)"; e.currentTarget.style.color = "rgba(243,236,224,0.7)"; }}
    >
      {label}
    </button>
  );
}

function Waterfall({ steps, max }) {
  let running = 0;
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
      {steps.map((s, i) => {
        const isStart = s.tone === "start";
        const isEnd = s.tone === "end";
        if (isStart) running = s.amt;
        else if (!isEnd) running = running + s.amt;
        const displayAmt = isEnd ? s.amt : s.amt;
        const isNegative = s.amt < 0;
        const widthPct = max > 0 ? Math.min(100, (Math.abs(isEnd ? s.amt : s.amt) / max) * 100) : 0;
        const color = isStart ? "var(--gold)" : isEnd ? "#8acaa0" : "rgba(243,236,224,0.55)";
        return (
          <div key={i} style={{ position: "relative" }}>
            <div style={{ display: "grid", gridTemplateColumns: "1fr auto auto", gap: 16, alignItems: "baseline", padding: "10px 0", borderBottom: i < steps.length - 1 ? "1px dashed rgba(243,236,224,0.1)" : "none" }}>
              <div>
                <div style={{ fontFamily: "var(--sans)", fontWeight: 600, fontSize: 14, color: isEnd ? "#8acaa0" : "var(--bg-paper)", letterSpacing: "-0.01em" }}>
                  {s.label}
                </div>
                {s.sub && <div className="dk-caption" style={{ marginTop: 2, color: "rgba(243,236,224,0.4)" }}>{s.sub}</div>}
              </div>
              <div style={{
                fontFamily: "var(--sans)",
                fontWeight: 700,
                fontSize: isEnd || isStart ? 22 : 16,
                color: isStart ? "var(--gold)" : isEnd ? "#8acaa0" : "#e88a7d",
                letterSpacing: "-0.015em",
                fontVariantNumeric: "tabular-nums",
              }}>
                {isNegative ? "−" : ""}${formatNum(Math.abs(displayAmt))}
              </div>
              <div style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.1em", color: "rgba(243,236,224,0.35)", minWidth: 70, textAlign: "right" }}>
                = ${formatNum(running)}
              </div>
            </div>
            <div style={{ height: 3, background: "rgba(243,236,224,0.04)", marginTop: 4 }}>
              <div style={{
                width: `${widthPct}%`,
                height: "100%",
                background: color,
                transition: "width 0.5s cubic-bezier(0.2,0.8,0.2,1)",
              }}></div>
            </div>
          </div>
        );
      })}
    </div>
  );
}

window.BeforeAfter = BeforeAfter;
window.NetNetSection = NetNetSection;
window.COMPARISONS = COMPARISONS;
