// Soulforce Arts — modals
const { useState: useStateM, useEffect: useEffectM, useRef: useRefM } = React;

// ─── "How did you hear about me?" — discreet one-tap chips on success screens ─
// Shown AFTER a signup, so it never adds friction to the conversion. One tap
// writes the answer to the existing EmailOctopus contact's attribution field
// (via /api/hear) and quietly thanks them. Renders nothing without an email.
const HEAR_OPTIONS = ['Word of mouth', 'Internet search', 'YouTube video', 'Social media conversation', 'Other'];
function HearChips({ email, source, onDark }) {
  const [picked, setPicked] = useStateM(null);
  if (!email) return null;
  const choose = (v) => {
    if (picked) return;
    setPicked(v);
    fetch('/api/hear', {
      method: 'POST', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email, value: v, source: source || '' }),
    }).catch(() => {});
  };
  const muted = onDark ? 'rgba(255,255,255,0.55)' : 'rgba(24,30,27,0.5)';
  const q = { fontSize: '12px', letterSpacing: '0.02em', color: muted, margin: '0 0 10px' };
  if (picked) return <p style={{ ...q, marginTop: '20px' }}>Thanks — good to know. 🙏</p>;
  const chip = {
    font: 'inherit', fontSize: '11.5px', letterSpacing: '0.03em',
    color: onDark ? 'rgba(255,255,255,0.72)' : 'rgba(24,30,27,0.62)',
    background: 'transparent',
    border: `1px solid ${onDark ? 'rgba(255,255,255,0.22)' : 'rgba(24,30,27,0.18)'}`,
    borderRadius: '999px', padding: '5px 12px', cursor: 'pointer', lineHeight: 1.3,
  };
  return (
    <div style={{ marginTop: '20px', textAlign: 'center' }}>
      <p style={q}>One quick thing — how did you find me?</p>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: '7px', justifyContent: 'center' }}>
        {HEAR_OPTIONS.map((o) => <button key={o} type="button" style={chip} onClick={() => choose(o)}>{o}</button>)}
      </div>
    </div>
  );
}

function ModalShell({ onClose, children }) {
  useEffectM(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => {
      document.removeEventListener('keydown', onKey);
      document.body.style.overflow = '';
    };
  }, [onClose]);
  return (
    <div className="modal-scrim" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="modal" role="dialog" aria-modal="true">
        <button className="close" onClick={onClose} aria-label="Close">×</button>
        {children}
      </div>
    </div>
  );
}

function FreeChapterModal({ onClose }) {
  const [step, setStep] = useStateM('gate'); // gate | read | done
  const [email, setEmail] = useStateM('');
  const submit = (e) => {
    e.preventDefault();
    if (!email.includes('@')) return;
    setStep('read');
  };

  if (step === 'read') {
    return (
      <ModalShell onClose={onClose}>
        <div className="reader">
          <div className="ch-num">About the Book</div>
          <h2 className="ch-title">Your art matters more than you know</h2>
          <p className="dropcap">
            <span className="dropcap-letter">M</span>any artists, musicians, and creatives share a secret fear: that their art
            doesn&rsquo;t really matter — that it isn&rsquo;t practical or useful enough to make a
            tangible contribution to a world in need. <strong>This couldn&rsquo;t be further from the truth.</strong>
          </p>
          <p>
            The purpose of art is to bring us more alive, to connect us with something bigger
            than our individual selves, to inspire, heal, and bring us together. These are
            universal human needs &mdash; and without them, life becomes a dry, dusty bone.
          </p>
          <p>
            <em>Soulforce</em> examines how the transformative energy that comes from facing
            creative challenges from a place of wholeness, aliveness, and connection can breathe
            new life into your work &mdash; and empower you to experience your art, your community,
            and the world anew.
          </p>
          <p>
            A must-read for fans of Julia Cameron and Alex Grey, it&rsquo;s a primer for a new
            generation of artists ready to claim their true potential as creative forces for change.
          </p>
          <div className="gate">
            <p>Your free first chapter is on its way to <strong>{email}</strong> &mdash; check your inbox.</p>
            <div style={{ display: 'flex', gap: '12px', flexWrap: 'wrap', justifyContent: 'center' }}>
              <a className="btn sm" href="https://a.co/d/0gpcNaOG" target="_blank" rel="noopener noreferrer">Get the book</a>
              <button className="btn outline sm" onClick={onClose}>Close</button>
            </div>
            <HearChips email={email} source="Book chapter" />
          </div>
        </div>
      </ModalShell>
    );
  }

  return (
    <ModalShell onClose={onClose}>
      <div className="kicker" style={{marginBottom:'16px'}}>The First Chapter</div>
      <h2 className="h-section">Where would you like it sent?</h2>
      <p className="lead">
        One chapter, no obligation. Read on the train, in the green room, between
        students. If it resonates, the rest of the book is waiting.
      </p>
      <form className="form" onSubmit={submit}>
        <div className="field">
          <label htmlFor="fc-name">Your name</label>
          <input id="fc-name" type="text" placeholder="Alex Renfro" />
        </div>
        <div className="field">
          <label htmlFor="fc-email">Email</label>
          <input id="fc-email" type="email" required placeholder="you@example.com"
            value={email} onChange={(e) => setEmail(e.target.value)} />
        </div>
        <div className="field">
          <label htmlFor="fc-inst">Your instrument (optional)</label>
          <select id="fc-inst" defaultValue="">
            <option value="" disabled>Choose one…</option>
            <option>Violin - Viola</option>
            <option>Cello - Bass</option>
            <option>Piano</option>
            <option>Guitar - Plucked Strings</option>
            <option>Voice</option>
            <option>Winds - Brass</option>
            <option>Percussion</option>
            <option>Other</option>
          </select>
        </div>
        <button type="submit" className="btn">Send me the chapter <span className="arr">→</span></button>
        <p className="fine">No spam. One thoughtful note a month, easy to unsubscribe.</p>
      </form>
    </ModalShell>
  );
}

function ExploratoryCallModal({ onClose }) {
  const calRef = useRefM(null);
  const CAL_URL = 'https://calendly.com/jarnold84/soulforce-arts-call';
  useEffectM(() => {
    const styled = CAL_URL + '?hide_gdpr_banner=1&background_color=fbfaf5&primary_color=bb8326&text_color=181e1b';
    const init = () => {
      if (window.Calendly && calRef.current) {
        calRef.current.innerHTML = '';
        window.Calendly.initInlineWidget({ url: styled, parentElement: calRef.current });
      }
    };
    const id = 'calendly-widget-js';
    let sc = document.getElementById(id);
    if (!sc) {
      sc = document.createElement('script');
      sc.id = id;
      sc.src = 'https://assets.calendly.com/assets/external/widget.js';
      sc.async = true;
      sc.onload = init;
      document.body.appendChild(sc);
    } else {
      init();
    }
    const t = setTimeout(init, 500);
    return () => clearTimeout(t);
  }, []);
  return (
    <ModalShell onClose={onClose}>
      <div className="kicker" style={{ marginBottom: '16px' }}>Talk with Joseph</div>
      <h2 className="h-section">A 30-minute conversation.</h2>
      <p className="lead">
        Not a sales call. We&rsquo;ll talk about what you&rsquo;re working on, what&rsquo;s
        in the way, and whether this work is right for you. If it is, I&rsquo;ll tell you
        the most useful next step. If it isn&rsquo;t, I&rsquo;ll tell you that too.
      </p>
      <div className="calendly-host" ref={calRef} aria-label="Scheduling calendar" />
      <p className="fine" style={{ marginTop: '14px' }}>
        Trouble loading the calendar?{' '}
        <a href={CAL_URL} target="_blank" rel="noopener noreferrer" style={{ color: 'var(--gold-warm)', borderBottom: '1px solid currentColor' }}>Open the scheduling page</a>.
        {' '}By video. No charge. No pitch.
      </p>
    </ModalShell>
  );
}

function StudioTeaserModal({ onClose, onCallCTA }) {
  return (
    <ModalShell onClose={onClose}>
      <div className="kicker" style={{marginBottom:'16px'}}>The Soulforce Arts Studio</div>
      <h2 className="h-section">A studio for serious musicians.</h2>
      <p className="lead">
        Ongoing weekly study with Joseph, in a small community of musicians on the
        same path. Live classes, working tools, guided practice — and the kind of
        attention you can&rsquo;t get from a course.
      </p>
      <div style={{
        display:'grid', gap:'14px', margin: '20px 0 24px',
        gridTemplateColumns: '1fr 1fr',
      }}>
        <div style={{padding:'18px', border:'1px solid rgba(26,31,29,0.12)'}}>
          <div className="kicker" style={{color:'var(--gold-warm)', marginBottom:'8px'}}>Weekly</div>
          <div style={{fontFamily:'var(--serif)', fontSize:'1.2rem'}}>Live class with Joseph</div>
          <div className="fine">Recorded if you can&rsquo;t make it live.</div>
        </div>
        <div style={{padding:'18px', border:'1px solid rgba(26,31,29,0.12)'}}>
          <div className="kicker" style={{color:'var(--gold-warm)', marginBottom:'8px'}}>20+</div>
          <div style={{fontFamily:'var(--serif)', fontSize:'1.2rem'}}>Tools for ease</div>
          <div className="fine">Growing library you&rsquo;ll use immediately.</div>
        </div>
        <div style={{padding:'18px', border:'1px solid rgba(26,31,29,0.12)'}}>
          <div className="kicker" style={{color:'var(--gold-warm)', marginBottom:'8px'}}>Always</div>
          <div style={{fontFamily:'var(--serif)', fontSize:'1.2rem'}}>A small circle</div>
          <div className="fine">Cohorts kept intentionally small.</div>
        </div>
        <div style={{padding:'18px', border:'1px solid rgba(26,31,29,0.12)'}}>
          <div className="kicker" style={{color:'var(--gold-warm)', marginBottom:'8px'}}>Month to month</div>
          <div style={{fontFamily:'var(--serif)', fontSize:'1.2rem'}}>No fixed term</div>
          <div className="fine">Stay as long as you&rsquo;re growing.</div>
        </div>
      </div>
      <p className="fine" style={{marginBottom:'14px'}}>
        Full details and pricing live on the Studio page. The shortest path in is
        a conversation.
      </p>
      <div style={{display:'flex', gap:'12px', flexWrap:'wrap'}}>
        <button className="btn" onClick={() => { onClose(); onCallCTA(); }}>
          Talk with Joseph <span className="arr">→</span>
        </button>
        <a className="linkish" href="/studio">Visit the Studio page →</a>
      </div>
    </ModalShell>
  );
}

// ─── Find Your Path — intake that returns a personalized recommendation ─────
const PATH_RECS = {
  pain: {
    tag: 'My recommendation',
    head: 'Start where the relief is.',
    body: 'It sounds like the body comes first. Come to the next Lab — it’s free, it’s live, and you’ll feel a real shift in 75 minutes. No commitment beyond showing up.',
    primary: { label: 'Join the free Lab', kind: 'lab', cls: 'btn' },
    secondary: { label: 'Read the first chapter free', kind: 'chapter' },
  },
  stuck: {
    tag: 'My recommendation',
    head: 'Let’s name what’s really in the way.',
    body: 'Plateaus usually aren’t about effort — they’re about a missing skill. Read the first chapter to see the frame, then come feel it for yourself at a free Lab.',
    primary: { label: 'Read the first chapter free', kind: 'chapter', cls: 'btn' },
    secondary: { label: 'Join the free Lab', kind: 'lab' },
  },
  skeptical: {
    tag: 'My recommendation',
    head: 'Don’t take my word for it — feel it.',
    body: 'Healthy skepticism is welcome here. The fastest way past it is the free Lab: 75 live minutes where you experience the work directly. Decide afterward.',
    primary: { label: 'Join the free Lab', kind: 'lab', cls: 'btn' },
    secondary: { label: 'Read the first chapter free', kind: 'chapter' },
  },
  ready: {
    tag: 'My recommendation',
    head: 'Let’s talk.',
    body: 'If you already know you want to go deeper, the best next step is a real conversation. Talk with me and we’ll find the right way in — no pitch, no pressure.',
    primary: { label: 'Talk with Joseph', kind: 'call', cls: 'btn' },
    secondary: { label: 'Or join a free Lab first', kind: 'lab' },
  },
};

function FindYourPathModal({ onClose, onRoute }) {
  const [step, setStep] = useStateM('form'); // form | done
  const [situation, setSituation] = useStateM('');
  const [name, setName] = useStateM('');
  const options = [
    { value: 'pain',      label: 'I\u2019m in pain or discomfort when I play' },
    { value: 'stuck',     label: 'I feel stuck or plateaued' },
    { value: 'skeptical', label: 'I\u2019m curious, but a little skeptical' },
    { value: 'ready',     label: 'I\u2019m ready to go deeper' },
  ];
  const submit = (e) => { e.preventDefault(); if (!situation) return; setStep('done'); };
  const rec = PATH_RECS[situation];

  if (step === 'done' && rec) {
    return (
      <ModalShell onClose={onClose}>
        <div className="kicker" style={{marginBottom:'16px'}}>{rec.tag}</div>
        <h2 className="h-section">{rec.head}</h2>
        <p className="lead">{name ? `${name}, ` : ''}{rec.body}</p>
        <p style={{fontFamily:'var(--sans)', fontStyle:'italic', color:'var(--gold-warm)', margin:'0 0 26px', fontSize:'1.05rem'}}>— Joseph</p>
        <div style={{display:'flex', gap:'16px', flexWrap:'wrap', alignItems:'center'}}>
          <button className={rec.primary.cls} onClick={() => { onClose(); onRoute(rec.primary.kind); }}>
            {rec.primary.label} <span className="arr">→</span>
          </button>
          <a className="linkish" href="#" onClick={(e) => { e.preventDefault(); onClose(); onRoute(rec.secondary.kind); }}>
            {rec.secondary.label}
          </a>
        </div>
      </ModalShell>
    );
  }

  return (
    <ModalShell onClose={onClose}>
      <div className="kicker" style={{marginBottom:'16px'}}>Where To Begin</div>
      <h2 className="h-section">Tell me about yourself.</h2>
      <p className="lead">
        A few quick things, and I&rsquo;ll point you to the right next step —
        something free, a class, or a conversation. No pitch, no pressure.
      </p>
      <form className="form" onSubmit={submit}>
        <div className="field">
          <label>What&rsquo;s most true for you right now?</label>
          <div className="choice-grid">
            {options.map((o) => (
              <button type="button" key={o.value}
                className={`choice ${situation === o.value ? 'active' : ''}`}
                onClick={() => setSituation(o.value)}>
                {o.label}
              </button>
            ))}
          </div>
        </div>
        <div className="field">
          <label htmlFor="fp-name">Your name</label>
          <input id="fp-name" type="text" placeholder="Alex Renfro"
            value={name} onChange={(e) => setName(e.target.value)} />
        </div>
        <div className="field">
          <label htmlFor="fp-inst">Your instrument (optional)</label>
          <select id="fp-inst" defaultValue="">
            <option value="" disabled>Choose one…</option>
            <option>Violin - Viola</option>
            <option>Cello - Bass</option>
            <option>Piano</option>
            <option>Guitar - Plucked Strings</option>
            <option>Voice</option>
            <option>Winds - Brass</option>
            <option>Percussion</option>
            <option>Other</option>
          </select>
        </div>
        <div className="field">
          <label htmlFor="fp-note">Anything you want me to know? (optional)</label>
          <textarea id="fp-note" placeholder="A sentence or two is plenty…" />
        </div>
        <button type="submit" className="btn" disabled={!situation} style={{opacity: situation ? 1 : 0.5}}>
          {situation ? <>Get my recommendation <span className="arr">→</span></> : 'Pick one above'}
        </button>
        <p className="fine">Goes straight to me. I read every one.</p>
      </form>
    </ModalShell>
  );
}

// ─── Tension Reset Lab — reserve a free seat, or get notified ───────────────
function LabModal({ onClose }) {
  const [step, setStep] = useStateM('form'); // form | done
  const [mode, setMode] = useStateM('reserve'); // reserve | notify
  const [email, setEmail] = useStateM('');
  const session = (() => {
    // Third Saturday of the month, auto-advancing to next month once it has passed.
    const thirdSat = (year, month) => {
      const first = new Date(year, month, 1);
      const toSat = (6 - first.getDay() + 7) % 7; // days from the 1st to the first Saturday
      return new Date(year, month, 1 + toSat + 14);
    };
    const now = new Date();
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
    let d = thirdSat(now.getFullYear(), now.getMonth());
    if (d < today) d = thirdSat(now.getFullYear(), now.getMonth() + 1);
    const label = d.toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric' });
    return `${label} · 12:00 pm ET`;
  })();
  const submit = (e) => {
    e.preventDefault();
    if (!email.includes('@')) return;
    const firstName = ((e.target.querySelector('#lab-name') || {}).value || '').trim();
    fetch('/api/subscribe', {
      method: 'POST', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email: email.trim(), firstName, tag: 'Tension Reset', source: mode === 'reserve' ? 'Lab reserve' : 'Lab notify' }),
    }).catch(() => {});
    setStep('done');
  };

  if (step === 'done') {
    return (
      <ModalShell onClose={onClose}>
        <div className="modal-success">
          <div className="check">✓</div>
          <div className="kicker" style={{justifyContent:'center', display:'inline-flex'}}>
            {mode === 'reserve' ? 'Your spot is saved' : 'You\u2019re on the list'}
          </div>
          <h2 className="h-section" style={{marginTop:'12px'}}>
            {mode === 'reserve' ? 'See you in the Lab.' : 'I\u2019ll be in touch.'}
          </h2>
          <p className="lead" style={{margin:'0 auto 24px'}}>
            {mode === 'reserve'
              ? <>You&rsquo;re in for <strong>{session}</strong>. A Zoom link is on its way to <strong>{email}</strong> — bring your instrument.</>
              : <>I&rsquo;ll email <strong>{email}</strong> the moment the next Musician&rsquo;s Tension Reset Lab is scheduled.</>}
          </p>
          <HearChips email={email} source="Tension Reset Lab" />
          <button className="btn" onClick={onClose}>Close</button>
        </div>
      </ModalShell>
    );
  }

  return (
    <ModalShell onClose={onClose}>
      <div className="kicker" style={{marginBottom:'16px'}}>The Musician&rsquo;s Tension Reset Lab</div>
      <h2 className="h-section">Come experience the work — free.</h2>
      <p className="lead">
        A free, live online drop-in. In 75 minutes I work with a few musicians in
        real time so you can feel the shift for yourself — no lecture, no pressure.
      </p>
      <div className="lab-session-chip">
        <span className="lab-dot"></span>
        Next session — <strong>{session}</strong>
      </div>
      <div className="seg" role="tablist" aria-label="Choose an option">
        <button type="button" className={`seg-btn ${mode === 'reserve' ? 'active' : ''}`} onClick={() => setMode('reserve')}>
          Reserve a seat
        </button>
        <button type="button" className={`seg-btn ${mode === 'notify' ? 'active' : ''}`} onClick={() => setMode('notify')}>
          Can&rsquo;t make it live
        </button>
      </div>
      <form className="form" onSubmit={submit}>
        <div className="field">
          <label htmlFor="lab-name">Your name</label>
          <input id="lab-name" type="text" placeholder="Alex Renfro" />
        </div>
        <div className="field">
          <label htmlFor="lab-email">Email</label>
          <input id="lab-email" type="email" required placeholder="you@example.com"
            value={email} onChange={(e) => setEmail(e.target.value)} />
        </div>
        <button type="submit" className="btn">
          {mode === 'reserve'
            ? <>Join the free Lab <span className="arr">→</span></>
            : <>Notify me of the next Lab <span className="arr">→</span></>}
        </button>
        <p className="fine">
          {mode === 'reserve'
            ? 'Free. Live on Zoom. Bring your instrument if you can.'
            : 'I\u2019ll only email you about future Labs — nothing else.'}
        </p>
      </form>
      <a href="/tensionreset" onClick={onClose}
        style={{ display: 'block', textAlign: 'center', marginTop: '18px',
          fontFamily: 'var(--sans)', fontSize: '12.5px', fontWeight: 500,
          letterSpacing: '0.04em', color: 'var(--gold-warm)' }}>
        Want the full details? See the Lab page →
      </a>
    </ModalShell>
  );
}

// ─── The Try-Harder Trap — $27 instant-access checkout ──────────────────────
function CheckoutModal({ onClose }) {
  const [step, setStep] = useStateM('form'); // form | done
  const [email, setEmail] = useStateM('');
  const submit = (e) => { e.preventDefault(); if (!email.includes('@')) return; setStep('done'); };

  if (step === 'done') {
    return (
      <ModalShell onClose={onClose}>
        <div className="modal-success">
          <div className="check">✓</div>
          <div className="kicker" style={{justifyContent:'center', display:'inline-flex'}}>You&rsquo;re in</div>
          <h2 className="h-section" style={{marginTop:'12px'}}>Check your inbox.</h2>
          <p className="lead" style={{margin:'0 auto 24px'}}>
            Your access link for <strong>The Try-Harder Trap</strong> is on its way to <strong>{email}</strong>.
            Grab your instrument — you&rsquo;ll want it for Part&nbsp;3.
          </p>
          <button className="btn" onClick={onClose}>Close</button>
        </div>
      </ModalShell>
    );
  }

  return (
    <ModalShell onClose={onClose}>
      <div className="kicker" style={{marginBottom:'16px'}}>Instant access</div>
      <h2 className="h-section">The Try-Harder Trap</h2>
      <div className="checkout-line">
        <div>
          <div className="checkout-item">45-minute on-demand class</div>
          <div className="checkout-sub">Watch immediately · 14-day refund</div>
        </div>
        <div className="checkout-price">$27</div>
      </div>
      <form className="form" onSubmit={submit}>
        <div className="field">
          <label htmlFor="co-name">Your name</label>
          <input id="co-name" type="text" placeholder="Alex Renfro" />
        </div>
        <div className="field">
          <label htmlFor="co-email">Email</label>
          <input id="co-email" type="email" required placeholder="you@example.com"
            value={email} onChange={(e) => setEmail(e.target.value)} />
        </div>
        <button type="submit" className="btn">Get instant access — $27 <span className="arr">→</span></button>
        <p className="fine">Secure checkout. Watch on your own schedule. 14-day, no-questions refund.</p>
      </form>
    </ModalShell>
  );
}

function GenericModal({ title, body, onClose }) {
  return (
    <ModalShell onClose={onClose}>
      <div className="kicker" style={{marginBottom:'16px'}}>Coming soon</div>
      <h2 className="h-section">{title}</h2>
      <p className="lead">{body}</p>
      <button className="btn ghost" onClick={onClose}>Close</button>
    </ModalShell>
  );
}

Object.assign(window, {
  FreeChapterModal, ExploratoryCallModal, StudioTeaserModal, GenericModal,
  FindYourPathModal, LabModal, CheckoutModal,
});
