// Slide-in contact panel — FORM ONLY (no email address is ever shown).
// Two variants share this engine:
//   variant="general"      — default site-wide / consulting form + the /contact page.
//   variant="commonground" — Enroll / Refer toggle that swaps the field set below.
// Names are always First / Last (separate). Required fields marked *.
//
// onSubmit receives a payload that always includes `success` (the toast copy for
// that variant/mode), so the copy lives here once and pages don't duplicate it.
//
// BACKEND ROUTING (note for build/launch — placeholder only in this prototype):
// when wired to Formspree or equivalent, route by payload.variant/mode —
//   commonground (enroll/refer) → intake workflow;
//   general (consulting / press) → business inbox.

function FieldText({ label, value, onChange, type = 'text', placeholder, required }) {
  return (
    <label>
      <span className="field-label">{label}{required ? ' *' : ''}</span>
      <input className="field-input" type={type} value={value}
        onChange={(e) => onChange(e.target.value)} placeholder={placeholder} required={required} />
    </label>
  );
}

function FieldSelect({ label, value, onChange, options, required, placeholder = 'Select one…' }) {
  return (
    <label>
      <span className="field-label">{label}{required ? ' *' : ''}</span>
      <select className="field-select" value={value} onChange={(e) => onChange(e.target.value)} required={required}>
        <option value="" disabled>{placeholder}</option>
        {options.map((o) => <option key={o} value={o}>{o}</option>)}
      </select>
    </label>
  );
}

function FieldArea({ label, value, onChange, placeholder, required }) {
  return (
    <label>
      <span className="field-label">{label}{required ? ' *' : ''}</span>
      <textarea className="field-textarea" value={value}
        onChange={(e) => onChange(e.target.value)} placeholder={placeholder} required={required} />
    </label>
  );
}

// ---- General / consulting form -------------------------------------------
function GeneralForm({ types, defaultType, onSubmit, onClose, hideCancel }) {
  const _types = types || [
    { id: 'training',     label: 'Training' },
    { id: 'curriculum',   label: 'Curriculum development' },
    { id: 'consultation', label: 'Consultation' },
    { id: 'press',        label: 'Press or speaking' },
    { id: 'other',        label: 'Other' },
  ];
  const initial = defaultType || _types[0].id;
  const [type, setType]   = React.useState(initial);
  const [first, setFirst] = React.useState('');
  const [last, setLast]   = React.useState('');
  const [org, setOrg]     = React.useState('');
  const [email, setEmail] = React.useState('');
  const [msg, setMsg]     = React.useState('');

  React.useEffect(() => { setType(initial); }, [initial]);

  const handleSubmit = (e) => {
    e.preventDefault();
    onSubmit?.({
      variant: 'general', type, first, last, org, email, msg,
      success: "Message sent. I'll reply within two business days.",
    });
    setFirst(''); setLast(''); setOrg(''); setEmail(''); setMsg('');
  };

  return (
    <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div>
        <span className="field-label">I'm reaching out about</span>
        <div className="field-radio-group" role="radiogroup">
          {_types.map((t) => (
            <label key={t.id} className={`field-radio${type === t.id ? ' is-on' : ''}`}>
              <input type="radio" name="inquiry-type" value={t.id}
                checked={type === t.id} onChange={() => setType(t.id)} />
              {t.label}
            </label>
          ))}
        </div>
      </div>
      <div className="field-row-2">
        <FieldText label="First name" value={first} onChange={setFirst} placeholder="First" required />
        <FieldText label="Last name"  value={last}  onChange={setLast}  placeholder="Last"  required />
      </div>
      <FieldText label="Organization (if applicable)" value={org} onChange={setOrg} placeholder="Court, agency, advocacy org…" />
      <FieldText label="Email" type="email" value={email} onChange={setEmail} placeholder="you@example.org" required />
      <FieldArea label="A few sentences about what you're working on" value={msg} onChange={setMsg}
        placeholder="Scope, audience, timing, any context that helps." required />
      <div style={{ display: 'flex', gap: 12, marginTop: 4 }}>
        <button className="btn-primary" type="submit">Send message</button>
        {hideCancel ? null : <button className="btn-secondary" type="button" onClick={onClose}>Cancel</button>}
      </div>
    </form>
  );
}

// ---- Common Ground: Enroll field set -------------------------------------
function EnrollForm({ onSubmit, onClose }) {
  const [first, setFirst] = React.useState('');
  const [last, setLast]   = React.useState('');
  const [phone, setPhone] = React.useState('');
  const [email, setEmail] = React.useState('');
  const [pref, setPref]   = React.useState('');
  const [brings, setBrings] = React.useState('');
  const [county, setCounty] = React.useState('');
  const [note, setNote]   = React.useState('');

  const handleSubmit = (e) => {
    e.preventDefault();
    onSubmit?.({
      variant: 'commonground', mode: 'enroll',
      first, last, phone, email, pref, brings, county, note,
      success: "Thanks for reaching out. I'll be in touch about next steps, usually within two business days.",
    });
  };

  return (
    <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div className="field-row-2">
        <FieldText label="First name" value={first} onChange={setFirst} placeholder="First" required />
        <FieldText label="Last name"  value={last}  onChange={setLast}  placeholder="Last"  required />
      </div>
      <div className="field-row-2">
        <FieldText label="Phone" type="tel" value={phone} onChange={setPhone} placeholder="(404) 555-0100" required />
        <FieldText label="Email" type="email" value={email} onChange={setEmail} placeholder="you@example.com" required />
      </div>
      <FieldSelect label="Preferred contact method" value={pref} onChange={setPref}
        options={['Text', 'Phone call', 'Email']} required />
      <FieldSelect label="What brings you here?" value={brings} onChange={setBrings}
        options={['Court or probation', 'A counselor or therapist', 'A partner or family member', 'On my own', 'Other']} required />
      <FieldText label="County, if in Georgia" value={county} onChange={setCounty} placeholder="e.g. Fulton, DeKalb" />
      <FieldArea label="Anything you'd like to share" value={note} onChange={setNote}
        placeholder="Optional. Anything that would help me understand your situation." />
      <div style={{ display: 'flex', gap: 12, marginTop: 4 }}>
        <button className="btn-primary" type="submit">Send</button>
        <button className="btn-secondary" type="button" onClick={onClose}>Cancel</button>
      </div>
    </form>
  );
}

// ---- Common Ground: Refer field set --------------------------------------
function ReferForm({ onSubmit, onClose }) {
  const [yFirst, setYFirst] = React.useState('');
  const [yLast, setYLast]   = React.useState('');
  const [yRole, setYRole]   = React.useState('');
  const [yEmail, setYEmail] = React.useState('');
  const [yPhone, setYPhone] = React.useState('');
  const [pFirst, setPFirst] = React.useState('');
  const [pLast, setPLast]   = React.useState('');
  const [pPhone, setPPhone] = React.useState('');
  const [pEmail, setPEmail] = React.useState('');
  const [paperwork, setPaperwork] = React.useState('');
  const [informed, setInformed]   = React.useState('');
  const [anything, setAnything]   = React.useState('');
  const [err, setErr] = React.useState('');

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!pPhone.trim() && !pEmail.trim()) {
      setErr("Please provide at least one way to reach the participant: phone or email.");
      return;
    }
    setErr('');
    onSubmit?.({
      variant: 'commonground', mode: 'refer',
      referrer: { first: yFirst, last: yLast, role: yRole, email: yEmail, phone: yPhone },
      participant: { first: pFirst, last: pLast, phone: pPhone, email: pEmail },
      paperwork, informed, anything,
      success: "Referral received. I'll follow up directly to schedule the enrollment meeting, usually within two business days.",
    });
  };

  return (
    <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <p className="field-subhead">About you</p>
      <div className="field-row-2">
        <FieldText label="Your first name" value={yFirst} onChange={setYFirst} placeholder="First" required />
        <FieldText label="Your last name"  value={yLast}  onChange={setYLast}  placeholder="Last"  required />
      </div>
      <FieldText label="Your role or organization" value={yRole} onChange={setYRole} placeholder="Probation officer, counselor, advocate…" required />
      <div className="field-row-2">
        <FieldText label="Your email" type="email" value={yEmail} onChange={setYEmail} placeholder="you@agency.org" required />
        <FieldText label="Your phone" type="tel" value={yPhone} onChange={setYPhone} placeholder="Optional" />
      </div>

      <p className="field-subhead">About the participant</p>
      <div className="field-row-2">
        <FieldText label="Participant's first name" value={pFirst} onChange={setPFirst} placeholder="First" required />
        <FieldText label="Participant's last name"  value={pLast}  onChange={setPLast}  placeholder="Last"  required />
      </div>
      <div className="field-row-2">
        <FieldText label="Participant's phone" type="tel" value={pPhone} onChange={setPPhone} placeholder="(404) 555-0100" />
        <FieldText label="Participant's email" type="email" value={pEmail} onChange={setPEmail} placeholder="name@example.com" />
      </div>
      <p className="field-hint" style={{ marginTop: -8 }}>Provide at least one: phone or email.</p>

      <FieldArea label="Relevant order or paperwork" value={paperwork} onChange={setPaperwork}
        placeholder="Note any court order or paperwork. You can send documents once we connect." />
      <FieldText label="How would you like to be kept informed?" value={informed} onChange={setInformed}
        placeholder="Optional. Attendance updates, completion, concerns…" />
      <FieldArea label="Anything else we should know" value={anything} onChange={setAnything}
        placeholder="Optional." />

      {err ? <p className="field-error">{err}</p> : null}
      <div style={{ display: 'flex', gap: 12, marginTop: 4 }}>
        <button className="btn-primary" type="submit">Send referral</button>
        <button className="btn-secondary" type="button" onClick={onClose}>Cancel</button>
      </div>
    </form>
  );
}

// ---- Common Ground variant: toggle wrapper -------------------------------
function CommonGroundContact({ open, defaultMode, onSubmit, onClose }) {
  const [mode, setMode] = React.useState(defaultMode === 'refer' ? 'refer' : 'enroll');
  React.useEffect(() => { setMode(defaultMode === 'refer' ? 'refer' : 'enroll'); }, [defaultMode, open]);

  const copy = mode === 'refer'
    ? {
        headline: 'Make a referral',
        intro: "Send the participant's details and any relevant paperwork, and I'll follow up directly to schedule their enrollment meeting. I respond within two business days.",
      }
    : {
        headline: 'Start the enrollment process',
        intro: "Tell me a little about your situation and I'll be in touch about next steps, usually within two business days.",
      };

  return (
    <React.Fragment>
      <p className="eyebrow" style={{ marginBottom: 0 }}>Common Ground</p>
      <h2 className="section-headline" style={{ marginBottom: 4, fontSize: 28 }}>{copy.headline}</h2>
      <div className="contact-toggle" style={{ marginBottom: 12 }} role="tablist">
        <button type="button" role="tab" aria-selected={mode === 'enroll'}
          className={mode === 'enroll' ? 'is-on' : ''} onClick={() => setMode('enroll')}>I'm enrolling</button>
        <button type="button" role="tab" aria-selected={mode === 'refer'}
          className={mode === 'refer' ? 'is-on' : ''} onClick={() => setMode('refer')}>I'm referring someone</button>
      </div>
      <p className="section-body" style={{ marginBottom: 8 }}>{copy.intro}</p>
      {mode === 'refer'
        ? <ReferForm onSubmit={onSubmit} onClose={onClose} />
        : <EnrollForm onSubmit={onSubmit} onClose={onClose} />}
    </React.Fragment>
  );
}

// ---- Panel shell ----------------------------------------------------------
function ContactPanel({
  open, onClose, onSubmit,
  variant = 'general',
  types, defaultType,
  defaultMode = 'enroll',
  eyebrow = 'Contact',
  headline = 'Start a conversation',
  intro,
}) {
  return (
    <React.Fragment>
      <div className={`contact-overlay${open ? ' is-open' : ''}`} onClick={onClose} />
      <aside className={`contact-panel${open ? ' is-open' : ''}`} aria-hidden={!open}>
        <button className="contact-close" onClick={onClose} aria-label="Close">×</button>
        {variant === 'commonground' ? (
          <CommonGroundContact open={open} defaultMode={defaultMode} onSubmit={onSubmit} onClose={onClose} />
        ) : (
          <React.Fragment>
            <p className="eyebrow" style={{ marginBottom: 0 }}>{eyebrow}</p>
            <h2 className="section-headline" style={{ marginBottom: 4, fontSize: 28 }}>{headline}</h2>
            <p className="section-body" style={{ marginBottom: 8 }}>
              {intro || "Tell me a bit about what you're working on and I'll reply within two business days."}
            </p>
            <GeneralForm types={types} defaultType={defaultType} onSubmit={onSubmit} onClose={onClose} />
          </React.Fragment>
        )}
      </aside>
    </React.Fragment>
  );
}

window.ContactPanel = ContactPanel;
window.GeneralForm = GeneralForm;
