/* global React, useDemoMode, demoPartnership, DemoChip, money, dayLabel */
// Partnership — where this course sits on the Sandbox journey:
//   Year 1 "Prove It" (zero cost, Sandbox-funded mats)
//   Year 2 "Commit"   (mat-kit reimbursement + the month-matched floor)
//   Year 3+ "Embed"   (permanent tee boxes, reduced split, Majors first-right,
//                      Insights tier included)
// Plus the founding-rate lock, and hand-raisers for hosting a Major or a
// corporate buyout (the fattest near-term checks in the model).

const JOURNEY = [
  { year: 'Year 1', title: 'Prove It', points: ['Zero course cost', 'Sandbox-funded turf mats', 'Cancel with 60-day notice'] },
  { year: 'Year 2', title: 'Commit', points: ['Mat kit reimbursed (15% off upfront, or ÷12 monthly)', 'Month-matched revenue floor — never go backwards', 'Reconciled quarterly'] },
  { year: 'Year 3+', title: 'Embed', points: ['Permanent SBX tee boxes, co-invested', 'Reduced split (12–13%)', 'First right to host Majors', 'Insights analytics tier included'] },
];

function leadKey(courseId, kind) { return `spp_mgr_lead_${kind}_${courseId}`; }
function useLeadSent(courseId, kind) {
  const [sent, setSent] = React.useState(() => {
    try { return localStorage.getItem(leadKey(courseId, kind)) === '1'; } catch (_) { return false; }
  });
  const mark = () => {
    try { localStorage.setItem(leadKey(courseId, kind), '1'); } catch (_) { /* noop */ }
    setSent(true);
  };
  return [sent, mark];
}

function PartnershipPanel({ course }) {
  const demo = useDemoMode();
  const joinedISO = demo ? demoPartnership(course.id).joinedAtISO : course.created_at;
  const monthsIn = joinedISO ? Math.max(0, (Date.now() - new Date(joinedISO).getTime()) / (30.44 * 864e5)) : 0;
  const yearIdx = Math.min(2, Math.floor(monthsIn / 12));
  const intoYear = (monthsIn % 12) / 12;
  const founding = (course.sandbox_take_pct != null ? course.sandbox_take_pct : 15) <= 12;
  const renewal = joinedISO ? new Date(new Date(joinedISO).setFullYear(new Date(joinedISO).getFullYear() + Math.floor(monthsIn / 12) + 1)) : null;

  const [majorSent, markMajor] = useLeadSent(course.id, 'major');
  const [corpSent, markCorp] = useLeadSent(course.id, 'corporate');
  const mailto = (subject) =>
    `mailto:partners@sbx.golf?subject=${encodeURIComponent(`${subject} — ${course.short_name}`)}&body=${encodeURIComponent(`Hi Sandbox,\n\nWe'd like to talk about ${subject.toLowerCase()} at ${course.name || course.short_name}.\n\n— ${course.short_name} management`)}`;

  return (
    <div style={{ maxWidth: 900, margin: '0 auto' }}>
      {/* Hero — open typography, matching the rest of the app */}
      <div style={{ position: 'relative' }}>
        {demo && <DemoChip/>}
        <div className="eyebrow">Your Partnership</div>
        <div className="display" style={{ fontSize: 30, color: 'var(--paper)', marginTop: 8 }}>
          {JOURNEY[yearIdx].year} · {JOURNEY[yearIdx].title}
        </div>
        <div style={{ fontSize: 13.5, color: 'var(--ink-muted)', marginTop: 10, lineHeight: 1.55 }}>
          Partner since {joinedISO ? dayLabel(joinedISO) : '—'}
          {renewal ? <> · next renewal {renewal.toLocaleDateString('en-US', { month: 'long', year: 'numeric' })}</> : null}.
        </div>
        <div style={{ display: 'flex', gap: 8, marginTop: 14, flexWrap: 'wrap' }}>
          {founding && (
            <span className="pill-mono" style={{ background: 'var(--cream)', color: 'var(--forest)' }}>
              ★ Founding Course · 12% Locked While You Renew
            </span>
          )}
          <span className="pill-mono" style={{ border: '1px solid var(--line-strong)', color: 'var(--ink-muted)' }}>
            Area Exclusivity
          </span>
        </div>
      </div>

      {/* The journey — an actual timeline: a rail with one node per year,
          the current year expanded (title, terms, progress bar), completed
          years shown with a check and their terms kept visible (not
          hidden), the year ahead shown muted as a preview. */}
      <div className="fade-in" style={{ marginTop: 36 }}>
        {JOURNEY.map((j, i) => {
          const current = i === yearIdx;
          const done = i < yearIdx;
          const last = i === JOURNEY.length - 1;
          return (
            <div key={j.year} style={{ display: 'flex', gap: 20 }}>
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', width: 16, flexShrink: 0 }}>
                <div style={{
                  width: current ? 15 : 11, height: current ? 15 : 11, borderRadius: 999, flexShrink: 0, marginTop: 5,
                  background: current || done ? 'var(--cream)' : 'var(--surface)',
                  border: current || done ? 'none' : '2px solid var(--line-strong)',
                  boxShadow: current ? '0 0 0 4px rgba(234,226,206,0.18)' : 'none',
                  transition: 'box-shadow var(--dur-slow) var(--ease)',
                }}/>
                {!last && <div style={{ width: 2, flex: 1, minHeight: 44, background: done ? 'var(--cream)' : 'var(--line)', marginTop: 4 }}/>}
              </div>
              <div style={{ flex: 1, minWidth: 0, paddingBottom: last ? 4 : 30 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
                  <span className="eyebrow">{j.year}</span>
                  {done && <span className="pill-mono" style={{ background: 'var(--surface-sunken)', color: 'var(--cream)' }}>✓ Complete</span>}
                  {current && <span className="pill-mono" style={{ background: 'var(--cream)', color: 'var(--forest)' }}>You Are Here</span>}
                </div>
                <div className="display" style={{ fontSize: current ? 24 : 18, color: current || done ? 'var(--paper)' : 'var(--ink-faint)', marginTop: 6 }}>
                  {j.title}
                </div>
                <ul style={{ margin: '9px 0 0', paddingLeft: 18, fontSize: 12.5, lineHeight: 1.75, color: current ? 'var(--ink-muted)' : 'var(--ink-faint)' }}>
                  {j.points.map(p => <li key={p}>{p}</li>)}
                </ul>
                {current && (
                  <div style={{ marginTop: 14, maxWidth: 320 }}>
                    <div style={{ height: 6, borderRadius: 99, background: 'var(--line)', overflow: 'hidden' }}>
                      <div style={{ width: `${Math.round(intoYear * 100)}%`, height: '100%', borderRadius: 99, background: 'var(--cream)', transition: 'width var(--dur-slow) var(--ease-out)' }}/>
                    </div>
                    <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--ink-faint)', marginTop: 6 }}>
                      {Math.round(intoYear * 12)} of 12 months into this year
                    </div>
                  </div>
                )}
              </div>
            </div>
          );
        })}
      </div>

      {/* Hand-raisers — two genuinely distinct opportunities, so a card
          each still earns its keep here. */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(320px, 1fr))', gap: 14, marginTop: 34 }}>
        <div className="card" style={{ padding: 22 }}>
          <div className="eyebrow">Host A Major</div>
          <div className="display" style={{ fontSize: 22, color: 'var(--paper)', marginTop: 8 }}>4 Per Year. Premium Venues.</div>
          <div style={{ fontSize: 12, color: 'var(--ink-faint)', marginTop: 8, lineHeight: 1.5 }}>
            Admin-run tournaments with entry fees, sponsors and a full field — embedded (Year 3+) courses get first hosting rights, but interest starts here.
          </div>
          <a href={mailto('Hosting a Sandbox Major')} onClick={markMajor} className="btn btn-forest" style={{ marginTop: 14, textDecoration: 'none', display: 'inline-flex' }}>
            {majorSent ? 'Request Sent ✓' : 'Raise Your Hand'}
          </a>
        </div>
        <div className="card" style={{ padding: 22 }}>
          <div className="eyebrow">Corporate Buyouts</div>
          <div className="display" style={{ fontSize: 22, color: 'var(--paper)', marginTop: 8 }}>One Outing ≈ 100+ Bookings.</div>
          <div style={{ fontSize: 12, color: 'var(--ink-faint)', marginTop: 8, lineHeight: 1.5 }}>
            Private events, never in public listings, priced on replacement value — the fattest near-term checks in the model, played on your course.
          </div>
          <a href={mailto('Corporate event at our course')} onClick={markCorp} className="btn btn-forest" style={{ marginTop: 14, textDecoration: 'none', display: 'inline-flex' }}>
            {corpSent ? 'Request Sent ✓' : 'Tell Sandbox We Want In'}
          </a>
        </div>
      </div>

      {/* What Sandbox never does — the trust block from the doc */}
      <div className="card" style={{ padding: 22, marginTop: 20, borderLeft: '3px solid var(--cream)' }}>
        <div className="eyebrow">What Sandbox Never Does</div>
        <div style={{ fontSize: 13, color: 'var(--ink-muted)', marginTop: 8, lineHeight: 1.7 }}>
          Never a % of your total (non-Sandbox) revenue · never a springing SaaS fee at renewal · never touches prime inventory
          or your existing customers · never forces a course discount to fund member perks. Your 85% is untouchable.
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { PartnershipPanel });
