// pro-waitlist-modal.jsx — ComposerOS PRO waitlist modal.
//
// Same structure, fields and button styles as the launch WaitlistModal,
// re-themed to the PRO "Be first in line when PRO ships" card
// (dark plum #2d2530, plum glow #6b5d7a, peach accent #d6b29e, ivory #f4ead5).
//
// Self-mounting: load this file with Babel like the other .jsx files and it
// adds its own root to <body>. Open it from anywhere with either:
//   window.dispatchEvent(new CustomEvent('cos-open-pro-waitlist'))
//   or any element with  href="#pro-waitlist"  or  data-pro-waitlist
//
// Submissions go through the site's existing window.submitToWeb3Forms()
// (same inbox as the other forms) and fall back to a mailto if it fails.

const PW_INK    = '#2d2530';
const PW_PLUM   = '#6b5d7a';
const PW_PEACH  = '#d6b29e';
const PW_IVORY  = '#f4ead5';
const PW_FONT   = "'Inter Tight',system-ui,-apple-system,BlinkMacSystemFont,sans-serif";
const PW_MONO   = "'JetBrains Mono',ui-monospace,monospace";
const PW_EVENT  = 'cos-open-pro-waitlist';

const PW_ROLES = ['Composer', 'Composer team / studio', 'Music editor', 'Producer / director', 'Student', 'Just curious'];
const PW_USAGE = ['Yes, I use it', 'Not yet'];
const PW_GROUPS = [
  { title:'Email', items:[
    { label:'Project-aware inbox',            desc:'Gmail threads filed to the right project' },
    { label:'Delivery-aware drafts',          desc:'Replies that know what is due and when' },
  ]},
  { title:'Recording', items:[
    { label:'Session & ensemble scheduling',  desc:'Studio dates and players in one place' },
    { label:'Take logging with timecode',     desc:'Every take noted and searchable' },
    { label:'Session budgets & reports',      desc:'Track spend, reports written for you' },
  ]},
  { title:'DAW', items:[
    { label:'Bounce review against picture',  desc:'Stems and stereo mixes against picture lock' },
    { label:'Cue markers synced to Cues',     desc:'Notes land on the right cue' },
  ]},
  { title:'Production', items:[
    { label:'Client review links',            desc:'Directors watch and comment in one place' },
    { label:'Timecoded revision notes',       desc:'Feedback pinned to the exact frame' },
  ]},
  { title:'Delivery', items:[
    { label:'Password-protected packages',    desc:'Mixes, stems, picture and docs in one link' },
    { label:'Download tracking',              desc:'Know when the client grabbed the files' },
  ]},
];

function ProWaitlistModal({ open, onClose }) {
  const [form, setForm] = React.useState({ name:'', email:'', role:'Composer', usage:'', features:[], why:'' });
  const [sent, setSent] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const dialogRef = React.useRef(null);

  React.useEffect(() => {
    if (!open) return;
    const onKey = e => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    setTimeout(() => { dialogRef.current && dialogRef.current.querySelector('input')?.focus(); }, 60);
    return () => { document.removeEventListener('keydown', onKey); document.body.style.overflow = prev; };
  }, [open, onClose]);
  React.useEffect(() => { if (open) setSent(false); }, [open]);

  if (!open) return null;

  const set = k => e => setForm(f => ({ ...f, [k]: e.target.value }));
  const toggleFeature = label => setForm(f => ({
    ...f, features: f.features.includes(label) ? f.features.filter(x => x !== label) : [...f.features, label],
  }));
  const valid = form.name.trim() && /\S+@\S+\.\S+/.test(form.email);

  const submit = async e => {
    e.preventDefault();
    if (!valid || sending) return;
    setSending(true);
    const fields = {
      subject: `PRO waitlist: ${form.name} (${form.role})`,
      from_name: form.name,
      email: form.email,
      list: 'ComposerOS PRO waitlist',
      role: form.role,
      uses_composeros_today: form.usage || '(no answer)',
      pro_tools_interested_in: form.features.length ? form.features.join(', ') : '(none selected)',
      hardest_part_of_final_mile: form.why || '(no answer)',
    };
    try {
      if (typeof window.submitToWeb3Forms !== 'function') throw new Error('no form handler');
      await window.submitToWeb3Forms(fields);
      setSent(true);
    } catch (_) {
      const body = Object.entries(fields).filter(([k]) => k !== 'subject').map(([k, v]) => `${k}: ${v}`).join('\n');
      window.location.href = `mailto:info@nemmgroup.ltd?subject=${encodeURIComponent(fields.subject)}&body=${encodeURIComponent(body)}`;
      setSent(true);
    }
    setSending(false);
  };

  const field = {
    width:'100%', padding:'12px 14px', borderRadius:10, boxSizing:'border-box',
    background:'rgba(244,234,213,0.05)', border:'1px solid rgba(244,234,213,0.16)',
    color:PW_IVORY, fontSize:15, fontFamily:PW_FONT, outline:'none',
    transition:'border-color 150ms, background 150ms',
  };
  const label = { fontSize:11, fontFamily:PW_MONO, letterSpacing:1, textTransform:'uppercase', color:'rgba(244,234,213,0.6)', marginBottom:7, display:'block' };
  const onFoc  = e => { e.target.style.borderColor = PW_PEACH; e.target.style.background = 'rgba(244,234,213,0.08)'; };
  const onBlur = e => { e.target.style.borderColor = 'rgba(244,234,213,0.16)'; e.target.style.background = 'rgba(244,234,213,0.05)'; };

  return (
    <div onMouseDown={e => { if (e.target === e.currentTarget) onClose(); }}
      style={{position:'fixed', inset:0, zIndex:300, display:'flex', alignItems:'center', justifyContent:'center',
        padding:20, background:'rgba(16,14,12,0.72)', backdropFilter:'blur(6px)', WebkitBackdropFilter:'blur(6px)',
        animation:'cos-pw-fade 180ms ease'}}>
      <div ref={dialogRef} role="dialog" aria-modal="true" aria-label="Join the PRO waitlist"
        style={{position:'relative', width:'min(540px, 100%)', maxHeight:'90vh', overflowY:'auto',
          background:`linear-gradient(180deg, rgba(107,93,122,0.55), rgba(107,93,122,0) 52%), ${PW_INK}`,
          border:'1px solid rgba(214,178,158,0.24)', borderRadius:18,
          padding:'clamp(26px, 4vw, 40px)', boxShadow:'0 30px 80px -24px rgba(0,0,0,0.7)',
          animation:'cos-pw-rise 220ms cubic-bezier(0.16,1,0.3,1)', fontFamily:PW_FONT, color:PW_IVORY}}>
        <button onClick={onClose} aria-label="Close"
          style={{position:'absolute', top:16, right:16, width:34, height:34, borderRadius:999,
            background:'rgba(244,234,213,0.06)', border:'1px solid rgba(244,234,213,0.14)', cursor:'pointer',
            display:'flex', alignItems:'center', justifyContent:'center', color:PW_IVORY}}>
          <svg width="14" height="14" viewBox="0 0 14 14"><g stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"><line x1="3" y1="3" x2="11" y2="11"/><line x1="11" y1="3" x2="3" y2="11"/></g></svg>
        </button>

        {sent ? (
          <div style={{textAlign:'center', padding:'18px 0'}}>
            <div style={{width:54, height:54, borderRadius:999, margin:'0 auto 18px', display:'flex', alignItems:'center', justifyContent:'center', background:'rgba(214,178,158,0.16)', border:`1px solid ${PW_PEACH}`}}>
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none"><polyline points="5,12.5 10,17.5 19,7" stroke={PW_PEACH} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
            </div>
            <h3 style={{margin:'0 0 10px', fontSize:24, fontWeight:500, color:PW_IVORY, letterSpacing:-0.5}}>You're on the PRO list.</h3>
            <p style={{margin:'0 auto', maxWidth:380, fontSize:15, lineHeight:1.6, color:'rgba(244,234,213,0.7)'}}>
              Thanks for telling us how you work. We'll reach out as PRO opens up, starting with the tools you picked.
            </p>
            <button onClick={onClose} style={{marginTop:24, padding:'12px 26px', borderRadius:999, background:PW_IVORY, color:PW_INK, border:'none', cursor:'pointer', fontSize:15, fontWeight:500, fontFamily:PW_FONT}}>Done</button>
          </div>
        ) : (
          <form onSubmit={submit}>
            <div style={{fontSize:11, fontFamily:PW_MONO, letterSpacing:1.6, textTransform:'uppercase', color:PW_PEACH, fontWeight:600, marginBottom:10}}>Early access · PRO</div>
            <h3 style={{margin:'0 0 8px', fontSize:'clamp(24px, 3.4vw, 30px)', fontWeight:450, letterSpacing:-0.8, color:PW_IVORY}}>
              Be first in line when PRO ships.
            </h3>
            <p style={{margin:'0 0 24px', fontSize:14.5, lineHeight:1.55, color:'rgba(244,234,213,0.66)'}}>
              Email, Recording, DAW, Production and Delivery are on the way. Tell us which ones you'd use first. It decides what we build first.
            </p>

            <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:16, marginBottom:16}} className="cos-form-row">
              <div>
                <label style={label} htmlFor="cos-pw-name">Name</label>
                <input id="cos-pw-name" style={field} value={form.name} onChange={set('name')} onFocus={onFoc} onBlur={onBlur} placeholder="Your name"/>
              </div>
              <div>
                <label style={label} htmlFor="cos-pw-email">Email</label>
                <input id="cos-pw-email" type="email" style={field} value={form.email} onChange={set('email')} onFocus={onFoc} onBlur={onBlur} placeholder="you@studio.com"/>
              </div>
            </div>

            <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:16, marginBottom:20}} className="cos-form-row">
              <div>
                <label style={label} htmlFor="cos-pw-role">I'm a…</label>
                <select id="cos-pw-role" style={{...field, appearance:'none', WebkitAppearance:'none', cursor:'pointer',
                  backgroundImage:`url("data:image/svg+xml,%3Csvg width='12' height='8' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M1 1.5L6 6.5L11 1.5' stroke='%23d6b29e' stroke-width='1.6' fill='none' stroke-linecap='round'/%3E%3C/svg%3E")`,
                  backgroundRepeat:'no-repeat', backgroundPosition:'right 14px center'}}
                  value={form.role} onChange={set('role')} onFocus={onFoc} onBlur={onBlur}>
                  {PW_ROLES.map(r => <option key={r} style={{color:'#1c1a17'}}>{r}</option>)}
                </select>
              </div>
              <div>
                <span style={label} id="cos-pw-usage-label">Using ComposerOS?</span>
                <div role="group" aria-labelledby="cos-pw-usage-label"
                  style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:6, padding:4, borderRadius:10,
                    background:'rgba(244,234,213,0.05)', border:'1px solid rgba(244,234,213,0.16)'}}>
                  {PW_USAGE.map(u => {
                    const sel = form.usage === u;
                    return (
                      <button type="button" key={u} aria-pressed={sel} onClick={() => setForm(f => ({ ...f, usage:u }))}
                        style={{padding:'8px 6px', borderRadius:7, border:'none', cursor:'pointer', fontFamily:PW_FONT,
                          fontSize:13.5, fontWeight: sel ? 600 : 500, transition:'background 150ms',
                          background: sel ? PW_PEACH : 'transparent', color: sel ? PW_INK : 'rgba(244,234,213,0.75)'}}>
                        {u}
                      </button>
                    );
                  })}
                </div>
              </div>
            </div>

            <div style={{marginBottom:20}}>
              <span style={{...label, marginBottom:4}}>Which PRO tools would you use first?</span>
              <div style={{fontSize:12.5, color:'rgba(244,234,213,0.5)', marginBottom:14}}>Select all that apply.</div>
              {PW_GROUPS.map((grp, gi) => (
                <div key={grp.title} style={{marginTop: gi === 0 ? 0 : 16}}>
                  <div style={{display:'flex', alignItems:'center', gap:10, marginBottom:9}}>
                    <span style={{fontSize:10, fontFamily:PW_MONO, letterSpacing:1.4, textTransform:'uppercase', color:PW_PEACH, fontWeight:600, whiteSpace:'nowrap'}}>{grp.title}</span>
                    <span style={{flex:1, height:1, background:'rgba(244,234,213,0.1)'}}/>
                  </div>
                  <div style={{display:'grid', gridTemplateColumns:'repeat(auto-fit, minmax(195px, 1fr))', gap:8}}>
                    {grp.items.map(it => {
                      const sel = form.features.includes(it.label);
                      return (
                        <button type="button" key={it.label} onClick={() => toggleFeature(it.label)} aria-pressed={sel}
                          onMouseOver={e => { if (!sel) { e.currentTarget.style.borderColor = 'rgba(244,234,213,0.32)'; e.currentTarget.style.background = 'rgba(244,234,213,0.07)'; } }}
                          onMouseOut={e => { if (!sel) { e.currentTarget.style.borderColor = 'rgba(244,234,213,0.13)'; e.currentTarget.style.background = 'rgba(244,234,213,0.04)'; } }}
                          style={{display:'flex', gap:10, alignItems:'flex-start', textAlign:'left', width:'100%', cursor:'pointer',
                            padding:'11px 12px', borderRadius:12, transition:'border-color 150ms, background 150ms', fontFamily:PW_FONT,
                            background: sel ? 'rgba(214,178,158,0.15)' : 'rgba(244,234,213,0.04)',
                            border:`1px solid ${sel ? PW_PEACH : 'rgba(244,234,213,0.13)'}`}}>
                          <span aria-hidden="true" style={{flexShrink:0, width:18, height:18, borderRadius:5, marginTop:1, boxSizing:'border-box',
                            border:`1.5px solid ${sel ? PW_PEACH : 'rgba(244,234,213,0.36)'}`, background: sel ? PW_PEACH : 'transparent',
                            display:'flex', alignItems:'center', justifyContent:'center', transition:'all 150ms'}}>
                            {sel && <svg width="11" height="11" viewBox="0 0 12 12" fill="none"><polyline points="2.5,6.5 5,9 9.5,3.5" stroke={PW_INK} strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round"/></svg>}
                          </span>
                          <span style={{display:'flex', flexDirection:'column', gap:3, minWidth:0}}>
                            <span style={{fontSize:13.5, fontWeight:500, lineHeight:1.2, color: sel ? PW_IVORY : 'rgba(244,234,213,0.9)'}}>{it.label}</span>
                            <span style={{fontSize:11.5, lineHeight:1.35, color: sel ? 'rgba(244,234,213,0.66)' : 'rgba(244,234,213,0.55)'}}>{it.desc}</span>
                          </span>
                        </button>
                      );
                    })}
                  </div>
                </div>
              ))}
            </div>

            <div style={{marginBottom:22}}>
              <label style={label} htmlFor="cos-pw-why">What's the hardest part of your final mile today? <span style={{textTransform:'none', letterSpacing:0, color:'rgba(244,234,213,0.45)'}}>(optional)</span></label>
              <textarea id="cos-pw-why" rows={3} style={{...field, resize:'vertical', minHeight:74, lineHeight:1.5}} value={form.why} onChange={set('why')} onFocus={onFoc} onBlur={onBlur} placeholder="Recording logistics, chasing notes, packaging stems…"/>
            </div>

            <button type="submit" disabled={!valid}
              style={{width:'100%', padding:'15px 24px', borderRadius:999, border:'none',
                background: valid ? PW_IVORY : 'rgba(244,234,213,0.18)',
                color: valid ? PW_INK : 'rgba(244,234,213,0.5)',
                fontSize:16, fontWeight:500, cursor: valid ? 'pointer' : 'not-allowed', fontFamily:PW_FONT,
                transition:'transform 150ms, background 150ms'}}
              onMouseOver={e => { if (valid) e.currentTarget.style.transform = 'scale(1.02)'; }}
              onMouseOut={e => e.currentTarget.style.transform = 'scale(1)'}>
              {sending ? 'Sending…' : 'Join the PRO waitlist'}
            </button>
            <p style={{margin:'14px 0 0', textAlign:'center', fontSize:12.5, color:'rgba(244,234,213,0.5)'}}>PRO is in development and not for sale yet.</p>
          </form>
        )}
      </div>
    </div>
  );
}

// Host: listens for the open event / #pro-waitlist links and renders the modal.
function ProWaitlistHost() {
  const [open, setOpen] = React.useState(false);
  React.useEffect(() => {
    const openIt = () => setOpen(true);
    const onClick = e => {
      const el = e.target.closest && e.target.closest('a[href="#pro-waitlist"], [data-pro-waitlist]');
      if (el) { e.preventDefault(); setOpen(true); }
    };
    window.addEventListener(PW_EVENT, openIt);
    document.addEventListener('click', onClick);
    if (location.hash === '#pro-waitlist') setOpen(true);
    return () => { window.removeEventListener(PW_EVENT, openIt); document.removeEventListener('click', onClick); };
  }, []);
  return <ProWaitlistModal open={open} onClose={() => setOpen(false)}/>;
}

// Self-mount once, with its own keyframes.
(function mountProWaitlist() {
  if (typeof document === 'undefined' || document.getElementById('cos-pro-waitlist-root')) return;
  const style = document.createElement('style');
  style.textContent = '@keyframes cos-pw-fade{from{opacity:0}to{opacity:1}}@keyframes cos-pw-rise{from{opacity:0;transform:translateY(14px) scale(0.98)}to{opacity:1;transform:none}}@media (max-width:560px){.cos-form-row{grid-template-columns:1fr !important}}';
  document.head.appendChild(style);
  const el = document.createElement('div');
  el.id = 'cos-pro-waitlist-root';
  document.body.appendChild(el);
  ReactDOM.createRoot(el).render(<ProWaitlistHost/>);
})();

if (typeof window !== 'undefined') Object.assign(window, { ProWaitlistModal, ProWaitlistHost });
