// RULES, what every producer needs to have in place
// Editorial: artist situation picker → 6 rules, with chips

const SITUATIONS = [
  { id: "nodeal", label: "No Deal", sub: "Beat was used. Nothing signed.", desc: "Beat was used. Nothing signed. No contract, no beat agreement, no Schedule A. This is informal territory, and more common than people admit." },
  { id: "indie-no", label: "Indie, No Distro", sub: "DIY artist · no distribution", desc: "Independent artist releasing on SoundCloud or YouTube only. No distribution to DSPs. Money exists, mostly via sync and direct sales, but you still need paperwork." },
  { id: "indie", label: "Indie with Distro", sub: "Distributing via DistroKid, etc.", desc: "Independent artist using DistroKid, TuneCore, or similar. Streaming royalties are now in play. Paperwork becomes essential, no label is doing it for you." },
  { id: "signed-indie", label: "Signed, Indie Label", sub: "Small label deal", desc: "Artist signed to an indie label. The label has admin, but assume nothing. Get your Schedule A filed, your splits documented, your registrations done." },
  { id: "major", label: "Major Label", sub: "Standard major deal", desc: "Major label deal with full admin chain. They will paper everything, but they will also try to optimize against you. Bring your own paper and your own lawyer." },
];

const RULES_BY_SITUATION = {
  nodeal: [
    { tag: "REALITY", tone: "red", title: "No contract is going to happen here", body: "A beat agreement and a Schedule A are not realistic in a true no-deal situation. The artist is not at a level where formal paperwork is the norm. Trying to enforce contracts here will end the relationship. Know that going in." },
    { tag: "PUBLISHING", tone: "gold", title: "Know who is on the beat, informally", body: "Even without a formal split sheet, document the writers involved for your own records. If the song ever takes off, you will need to know who contributed so you can pursue registration retroactively. Write it down. Save the session files. Keep receipts." },
    { tag: "PRO", tone: "gold", title: "Only register if it reaches 100,000+ streams", body: "Registering a song with your PRO before it hits around 100,000 streams is not worth the administrative overhead. Below that threshold, treat the placement as experience and a portfolio credit. If it crosses that number, then register it with BMI, ASCAP, or your regional PRO.", tooltip: { kind: "pub" } },
    { tag: "MECHANICALS", tone: "green", title: "Skip The MLC at this stage", body: "Not worth registering mechanicals at this level. If the song starts generating real streaming numbers (think 100K+), revisit. Until then, the administrative effort outweighs the return.", tooltip: { kind: "master" } },
    { tag: "PAYMENT", tone: "payment", title: "Producer fee depends on their listener count", body: "Whether you can even charge a fee depends on the artist's monthly listeners. Use the Producer Fee calculator above, select their tier and your track record. An artist with under 100K listeners is an Independent. Understand your rate going in, even if it is $0 and the value is the credit." },
    { tag: "WATCH FOR", tone: "red", title: "Don't give away too much for nothing", body: "A no-deal situation is worth it when the artist has real momentum or the credit opens doors. If neither of those is true, think carefully about what you are trading away. Your time and beats are finite." },
  ],
  "indie-no": [
    { tag: "PAPERWORK", tone: "gold", title: "Get a real beat agreement in writing", body: "Even with a DIY artist, a one-page beat agreement is feasible and protects both sides. Specify use, exclusivity, and what happens if the song crosses a streaming threshold." },
    { tag: "PUBLISHING", tone: "gold", title: "Split sheet, signed, before the song is finished", body: "Easier to negotiate when it's still in the room. Document publishing splits early. Use a co-write agreement template, they're free." },
    { tag: "PRO", tone: "gold", title: "Register with a PRO if you haven't already", body: "Performance royalties exist even at small scale. Live shows, college radio, sync. Register with BMI, ASCAP, or SOCAN, it's free and takes 15 minutes." },
    { tag: "MECHANICALS", tone: "green", title: "Skip MLC until streaming distribution starts", body: "If they're not on Spotify yet, mechanicals aren't accruing. Park this. Revisit when they distribute." },
    { tag: "PAYMENT", tone: "payment", title: "Fee should be modest but real", body: "Around $50–300 per beat depending on your credits. Don't quote a label rate, but don't give it away either. Trade for a credit, not for nothing." },
    { tag: "WATCH FOR", tone: "red", title: "Sync windows are surprisingly common here", body: "DIY artists get into TV/film placements via direct supervisors. If your work shows up in a sync, you want master and pub registered correctly, even at this level." },
  ],
  indie: [
    { tag: "PAPERWORK", tone: "gold", title: "Beat agreement AND Schedule A", body: "Once a song is on DSPs, all the money streams turn on. Get both papers signed before release. The distributor needs the Schedule A to pay out correctly." },
    { tag: "PUBLISHING", tone: "gold", title: "50% of writer share for the music you wrote", body: "If you composed the beat, you wrote half the song. The standard publishing split is 50% to the producer / 50% to the artist on the music side. Don't negotiate down." },
    { tag: "PRO", tone: "gold", title: "Register the song with your PRO immediately", body: "Streaming generates performance royalties from the first play. Register it within 30 days of release. Use the ISRC and ISWC from the distributor." },
    { tag: "MECHANICALS", tone: "green", title: "Sign up with The MLC if you're US-based", body: "Mechanical royalties from US streams are paid out through The MLC. Free to register. Money is sitting there if you don't." },
    { tag: "PAYMENT", tone: "payment", title: "Fee is real now, and so is the points conversation", body: "Quote a producer fee in the $500–$3,000 range depending on credits. Plus 2–3 points on the master. Plus 50% publishing on what you wrote. All three." },
    { tag: "WATCH FOR", tone: "red", title: "Distros 'helpfully' register publishing for the artist", body: "Some distros auto-register publishing under the artist's name. Catch this. Your publishing share is yours, don't let a checkbox sign it away." },
  ],
  "signed-indie": [
    { tag: "PAPERWORK", tone: "gold", title: "Producer agreement signed before delivery", body: "Indie label will draft this. Read it. Or have a music lawyer read it. The standard is: producer fee, 3–5 points, 50% pub. Anything less is the start of a negotiation, not the end." },
    { tag: "PUBLISHING", tone: "gold", title: "Publishing controlled, not assigned", body: "You want to control your publishing share, not assign it to the label's publishing arm. Different deal, different money. Be explicit." },
    { tag: "PRO + MLC", tone: "gold", title: "Full registration chain, no skips", body: "PRO + MLC + SoundExchange. The label admin should handle it but verify. Quarterly. Money disappears quietly when nobody is checking." },
    { tag: "MASTER POINTS", tone: "publish", title: "Negotiate points, not just fee", body: "On a signed deal, points are the money. 3–5 points on the master, escalating on follow-ups. The fee is the appetizer. The points are the meal." },
    { tag: "PAYMENT", tone: "payment", title: "Advance against royalties is standard", body: "Producer fee here is structured as an advance recoupable against your royalty share. Make sure the recoupment is from YOUR share only, not cross-collateralized." },
    { tag: "WATCH FOR", tone: "red", title: "360 deals leaking into producer agreements", body: "Some indie labels are slipping 360-style language into producer paperwork, claims on touring, merch, sync. Strike it. Producer agreements are for the recording, period." },
  ],
  major: [
    { tag: "PAPERWORK", tone: "gold", title: "Get a music attorney before you sign anything", body: "At this level, the cost of an attorney is rounding error compared to what's at stake. Non-negotiable. Walk away from any deal where they pressure you to skip this." },
    { tag: "PUBLISHING", tone: "gold", title: "50% writer share, and keep your own admin", body: "Major label deals routinely try to acquire your publishing or push you into their pub arm. Resist. Keep an independent publishing admin. Long game wins." },
    { tag: "PRO + MLC + SX", tone: "gold", title: "All three. Verified. Audited.", body: "Performance, mechanical, digital performance, three separate registration chains. The label admin will set up most of it. Audit yearly. Audits find money roughly 60% of the time." },
    { tag: "MASTER POINTS", tone: "publish", title: "5+ points on the master, escalators on releases 2+", body: "A-tier credits at a major: 5+ points base, with escalators. Plus the producer fee advance. Plus 50% pub on what you wrote. Anything less and you're being negotiated against, not with." },
    { tag: "PAYMENT", tone: "payment", title: "Fee structured as a recoupable advance", body: "Standard at majors. The advance is real money up front. Royalties begin paying out once advance is recouped from your master share only. Confirm in writing." },
    { tag: "WATCH FOR", tone: "red", title: "Buyouts disguised as 'simplified' deals", body: "Watch for language that converts a points deal into a buyout under another name. Especially common in DSP-exclusive or playlist-strategy deals. Read every clause." },
  ],
};

const COMPARISON_INDEX = { nodeal: 0, "indie-no": 1, indie: 2, "signed-indie": 3, major: 4 };

const OUTCOME_FIELDS = [
  { key: "fee", label: "Producer fee" },
  { key: "pub", label: "Publishing" },
  { key: "master", label: "Master" },
  { key: "out", label: "Outcome" },
];

function SituationOutcome({ sitId }) {
  const comparisons = window.COMPARISONS;
  if (!comparisons) return null;
  const c = comparisons[COMPARISON_INDEX[sitId]];
  if (!c) return null;

  return (
    <div className="rules-outcome">
      <div className="rules-outcome-head caption">
        <span>Before vs after</span>
        <span>{c.deal}</span>
      </div>
      <div className="rules-outcome-grid">
        <div className="rules-outcome-col">
          <span className="caption">Without paperwork</span>
          {OUTCOME_FIELDS.map(({ key, label }) => (
            <div key={key} className="rules-outcome-row">
              <span className="rules-outcome-label">{label}</span>
              <span className="rules-outcome-val">{c.before[key]}</span>
            </div>
          ))}
        </div>
        <div className="rules-outcome-col rules-outcome-after">
          <span className="caption">With paperwork</span>
          {OUTCOME_FIELDS.map(({ key, label }) => (
            <div key={key} className="rules-outcome-row">
              <span className="rules-outcome-label">{label}</span>
              <span className="rules-outcome-val">{c.after[key]}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function Rules() {
  const [sit, setSit] = React.useState("nodeal");
  const rules = RULES_BY_SITUATION[sit];
  const sitObj = SITUATIONS.find((s) => s.id === sit);

  return (
    <section className="section rule-top" id="rules">
      <div className="page">
        <div className="grid-12" style={{ alignItems: "end", marginBottom: 56 }}>
          <div style={{ gridColumn: "span 1" }} className="hide-mobile">
            <span className="vert">PLAYBOOK · 06 RULES</span>
          </div>
          <div style={{ gridColumn: "span 7" }}>
            <span className="eyebrow">The Playbook</span>
            <h2 className="h-section" style={{ marginTop: 16 }}>
              Six rules.<br/>
              <em>Per situation.</em>
            </h2>
          </div>
          <div style={{ gridColumn: "span 4" }}>
            <p className="lede">
              Producers leave money uncollected because they applied the wrong rules to the wrong situation. Pick the artist's reality. Read the rules for it.
            </p>
          </div>
        </div>

        {/* Situation picker — Liquid Glass segmented control */}
        <div style={{ marginBottom: 4 }}>
          <GlassSegmented
            full
            items={SITUATIONS.map((s, i) => ({
              id: s.id,
              num: String(i + 1).padStart(2, "0"),
              label: s.label,
              sub: s.sub,
            }))}
            active={sit}
            onChange={setSit}
            ariaLabel="Artist situation"
          />
        </div>

        {/* Situation description */}
        <div className="grid-12" style={{ padding: "32px 0 24px", borderBottom: "1px solid var(--rule)" }}>
          <span className="caption" style={{ gridColumn: "span 2" }}>About this chapter</span>
          <p className="pull-serif" style={{ gridColumn: "span 8", fontSize: "clamp(18px, 1.8vw, 24px)", lineHeight: 1.35, margin: 0, color: "var(--ink-2)" }}>
            {sitObj.desc}
          </p>
          <span className="caption" style={{ gridColumn: "span 2", textAlign: "right" }}>{rules.length} rules</span>
        </div>

        <SituationOutcome sitId={sit} />

        {/* Rules list */}
        <div style={{ marginTop: 0 }}>
          {rules.map((r, i) => (
            <RuleRow key={i} rule={r} index={i} />
          ))}
        </div>
      </div>
    </section>
  );
}

function RuleRow({ rule, index }) {
  const [open, setOpen] = React.useState(false);
  return (
    <Reveal>
      <article style={{
        display: "grid",
        gridTemplateColumns: "80px 140px 1fr",
        gap: 32,
        padding: "32px 0",
        borderBottom: "1px solid var(--rule)",
        alignItems: "start",
      }}>
        <div style={{ fontFamily: "var(--mono)", fontSize: 11, color: "var(--ink-3)", letterSpacing: "0.16em", paddingTop: 6 }}>
          {String(index + 1).padStart(2, "0")}
        </div>
        <div style={{ paddingTop: 4 }}>
          <span className={`chip ${rule.tone}`}>{rule.tag}</span>
        </div>
        <div>
          <h3 style={{ fontFamily: "var(--sans)", fontWeight: 700, fontSize: "clamp(20px, 2.2vw, 28px)", letterSpacing: "-0.02em", margin: 0, marginBottom: 12, color: "var(--ink)" }}>
            {rule.title}
          </h3>
          <p className="body-text" style={{ fontSize: 16, lineHeight: 1.55, maxWidth: "68ch", margin: 0 }}>
            {rule.body}
          </p>
          {rule.tooltip && (
            <div style={{ marginTop: 14 }}>
              <button onClick={() => setOpen((o) => !o)} style={{
                background: "transparent",
                border: "1px dashed var(--rule-gold)",
                color: "var(--gold)",
                fontFamily: "var(--mono)",
                fontSize: 10,
                letterSpacing: "0.16em",
                padding: "6px 10px",
                cursor: "pointer",
                textTransform: "uppercase",
              }}>
                {open ? "− Hide the math" : "ⓘ Why 100,000? See the math"}
              </button>
              {open && <ThresholdMath kind={rule.tooltip.kind} />}
            </div>
          )}
        </div>
      </article>
    </Reveal>
  );
}

// Mini calculator showing why ~100K streams is the worth-your-time threshold
function ThresholdMath({ kind }) {
  const [streams, setStreams] = React.useState(100_000);
  const [indie, setIndie] = React.useState(true);

  // Rough industry math — publishing pool ~$600–800/million streams total
  const pubPerK = 0.7;
  const masterPerK = indie ? 4.0 : 1.5; // indie keeps more vs label takes most

  const pub = (streams / 1000) * pubPerK;
  const mst = (streams / 1000) * masterPerK;
  const value = kind === "pub" ? pub : mst;

  // Producer share, assume 50% of pub or 3 master points
  const yourCut = kind === "pub" ? value * 0.5 : value * 0.03;

  return (
    <div style={{ marginTop: 12, padding: "18px 20px", border: "1px solid var(--rule-gold)", background: "rgba(212,166,74,0.04)" }}>
      <p className="body-text" style={{ fontSize: 14, lineHeight: 1.55, color: "var(--ink-2)", margin: 0 }}>
        100,000 isn't a rule, it's a <span className="gold">value-of-time</span> threshold. Filing takes 15–30 minutes per song. Below this number, the {kind === "pub" ? "publishing pool" : "master pool"} on a single song is too small to make that admin time worth it. Above it, the math flips. Drag the slider:
      </p>

      {kind === "master" && (
        <div style={{ marginTop: 14 }}>
          <GlassSegmented
            items={[
              { id: "indie", label: "Independent artist" },
              { id: "signed", label: "Signed (label takes most)" },
            ]}
            active={indie ? "indie" : "signed"}
            onChange={(id) => setIndie(id === "indie")}
            ariaLabel="Artist deal type"
          />
        </div>
      )}

      <div style={{ marginTop: 16, display: "grid", gridTemplateColumns: "1fr auto", gap: 16, alignItems: "center" }}>
        <input
          type="range"
          min="1000"
          max="10000000"
          step="1000"
          value={streams}
          onChange={(e) => setStreams(Number(e.target.value))}
          style={{ width: "100%", accentColor: "var(--gold)" }}
        />
        <div style={{ fontFamily: "var(--mono)", fontSize: 12, color: "var(--gold)", minWidth: 120, textAlign: "right" }}>
          {formatNum(streams)} streams
        </div>
      </div>

      <div style={{ marginTop: 16, display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 12 }}>
        <Stat label={`${kind === "pub" ? "Publishing pool" : "Master pool"}`} value={`$${formatNum(value)}`} />
        <Stat label="Your cut (est.)" value={`$${formatNum(yourCut)}`} gold />
        <Stat label="vs. 15 min admin" value={value < 50 ? "not worth it" : value < 200 ? "borderline" : "register it"} flag={value >= 200} />
      </div>

      <p className="caption" style={{ marginTop: 14, color: "var(--ink-3)" }}>
        ★ Rough industry numbers. Real payouts vary by country, royalty type, and platform mix. The point isn't precision, it's <span style={{ color: "var(--gold)" }}>knowing roughly when filing crosses from chore to obvious</span>.
      </p>
    </div>
  );
}

function Stat({ label, value, gold, flag }) {
  return (
    <div style={{ padding: "10px 12px", border: "1px solid var(--rule)", background: "rgba(255,255,255,0.02)" }}>
      <div className="caption">{label}</div>
      <div style={{
        fontFamily: "var(--sans)",
        fontWeight: 700,
        fontSize: 17,
        letterSpacing: "-0.015em",
        color: flag ? "#8acaa0" : gold ? "var(--gold)" : "var(--ink)",
        marginTop: 2,
        fontVariantNumeric: "tabular-nums",
      }}>
        {value}
      </div>
    </div>
  );
}

window.Rules = Rules;
