/* Contact — form + chapter info + officer contacts. Exports window.Pages.contact */
const conDS = window.WKYHBHutchinsonBellDesignSystem_7985db || {};

function ContactPage({ prefillTo }) {
  const { Button, Input } = conDS; const U = window.U; const data = window.WKYHB;
  // Each recipient routes to a generic address (so it survives turnover) and
  // CCs info@ for a shared record. General inquiry goes straight to info@.
  const recipients = [
    { label: 'General inquiry', to: data.org.email },
    ...data.officers.map((o) => ({ label: `${o.name} · ${o.role}`, name: o.name, to: o.email, cc: data.org.email })),
    ...data.board.map((b) => ({ label: `${b.name} · Board of Directors`, name: b.name, to: b.email, cc: data.org.email })),
  ];
  const matched = prefillTo ? recipients.find((r) => r.label.startsWith(prefillTo)) : null;
  const [form, setForm] = React.useState({ name: '', email: '', to: (matched || recipients[0]).label, message: '' });
  const [err, setErr] = React.useState({});
  const [done, setDone] = React.useState(false);

  React.useEffect(() => { if (matched) setForm((f) => ({ ...f, to: matched.label })); }, [prefillTo]);

  const pickStyle = { display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12, background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--radius-md)', padding: '12px 16px', cursor: 'pointer', textAlign: 'left' };
  const pickName = { fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 14.5, color: 'var(--text-strong)', whiteSpace: 'nowrap' };
  const pickRole = { fontFamily: 'var(--font-condensed)', textTransform: 'uppercase', letterSpacing: '0.08em', fontSize: 11.5, color: 'var(--bell-crimson)', fontWeight: 600, whiteSpace: 'nowrap' };

  const submit = (e) => {
    e.preventDefault();
    const next = {};
    if (!form.name.trim()) next.name = 'Please enter your name.';
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(form.email)) next.email = 'Enter a valid email address.';
    if (!form.message.trim()) next.message = 'Please add a short message.';
    setErr(next);
    if (Object.keys(next).length === 0) {
      const rec = recipients.find((r) => r.label === form.to) || recipients[0];
      const subject = `Website message — ${rec.name || rec.label}`;
      const body = `Name: ${form.name}\nEmail: ${form.email}\nRegarding: ${rec.label}\n\n${form.message}`;
      window.location.href = U.mailto(rec.to, subject, body, rec.cc);
      setDone(true);
    }
  };

  return (
    <React.Fragment>
      <U.PageHeader eyebrow="Contact" title="We'd love to hear from you" lead="Questions about events, membership, scholarships, or giving? Reach out and a chapter officer will get back to you." />
      <U.Section bg="surface">
        <U.Container>
          <div className="wk-2col" style={{ display: 'grid', gridTemplateColumns: '1fr 0.8fr', gap: 'var(--space-8)', alignItems: 'start' }}>
            {/* Form */}
            <div style={{ background: 'var(--surface-paper)', borderRadius: 'var(--radius-lg)', border: '1px solid var(--border)', boxShadow: 'var(--shadow-md)', borderTop: '4px solid var(--bell-crimson)', padding: 'var(--space-7)' }}>
              {done ? (
                <U.SuccessPanel title="Almost there — send your message" onReset={() => { setDone(false); setForm({ name: '', email: '', to: recipients[0].label, message: '' }); }} resetLabel="Write another">
                  Your email app should have opened with your message ready to send to whoever you picked, copying {data.org.email}. Just hit send and we'll get back to you. (Didn't open? Email us directly at {data.org.email}.)
                </U.SuccessPanel>
              ) : (
                <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }} className="wk-2col">
                    <Input label="Full name" required value={form.name} error={err.name} onChange={(e) => setForm({ ...form, name: e.target.value })} placeholder="Your name" />
                    <Input label="Email" type="email" required value={form.email} error={err.email} onChange={(e) => setForm({ ...form, email: e.target.value })} placeholder="you@email.com" />
                  </div>
                  <U.Select label="Send to" value={form.to} onChange={(e) => setForm({ ...form, to: e.target.value })}>
                    {recipients.map((r) => <option key={r.label}>{r.label}</option>)}
                  </U.Select>
                  <U.TextArea label="Message" required value={form.message} onChange={(e) => setForm({ ...form, message: e.target.value })} placeholder="How can we help?" />
                  {err.message && <span style={{ fontSize: 'var(--text-xs)', color: 'var(--bell-crimson)', marginTop: -8 }}>{err.message}</span>}
                  <Button type="submit" size="lg" fullWidth>Send message</Button>
                  <p style={{ fontFamily: 'var(--font-body)', fontSize: 12.5, color: 'var(--text-muted)', margin: 0, textAlign: 'center', lineHeight: 1.5 }}>
                    This opens your email app with your message addressed to the person you selected and copied to {data.org.email} — no account needed. Prefer to write us directly? Email <a href={`mailto:${data.org.email}`} style={{ color: 'var(--bell-crimson)', fontWeight: 600, textDecoration: 'none' }}>{data.org.email}</a>.
                  </p>
                </form>
              )}
            </div>

            {/* Info */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-6)' }}>
              <div>
                <U.Eyebrow>Chapter</U.Eyebrow>
                <div style={{ fontFamily: 'var(--font-body)', fontSize: 15.5, lineHeight: 1.7, color: 'var(--text-body)', marginTop: 8 }}>
                  <a href={`mailto:${data.org.email}`} style={{ color: 'var(--bell-crimson)', textDecoration: 'none', fontWeight: 700 }}>{data.org.email}</a><br />
                  {data.org.address}<br />
                  <a href={data.links.facebook} target="_blank" rel="noopener" style={{ color: 'var(--bell-crimson)', textDecoration: 'none', fontWeight: 600, display: 'inline-flex', alignItems: 'center', gap: 6, verticalAlign: 'middle' }}><U.IconFacebook size={15} />Facebook <U.IconExternal /></a> &nbsp;·&nbsp;
                  <a href={data.links.instagram} target="_blank" rel="noopener" style={{ color: 'var(--bell-crimson)', textDecoration: 'none', fontWeight: 600, display: 'inline-flex', alignItems: 'center', gap: 6, verticalAlign: 'middle' }}><U.IconInstagram size={15} />Instagram <U.IconExternal /></a>
                </div>
              </div>
              <div>
                <U.Eyebrow>Officers</U.Eyebrow>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 10 }}>
                  {data.officers.map((o) => (
                    <button key={o.name} onClick={() => setForm((f) => ({ ...f, to: `${o.name} · ${o.role}` }))} style={pickStyle}>
                      <span style={pickName}>{o.name}</span>
                      <span style={pickRole}>{o.role}</span>
                    </button>
                  ))}
                </div>
                <div style={{ marginTop: 'var(--space-5)' }}><U.Eyebrow>Board of Directors</U.Eyebrow></div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 10 }}>
                  {data.board.map((b) => (
                    <button key={b.name} onClick={() => setForm((f) => ({ ...f, to: `${b.name} · Board of Directors` }))} style={pickStyle}>
                      <span style={pickName}>{b.name}</span>
                      <span style={pickRole}>Board</span>
                    </button>
                  ))}
                </div>
              </div>
              <div style={{ background: 'var(--ink)', borderRadius: 'var(--radius-lg)', padding: 'var(--space-6)', color: '#fff' }}>
                <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 'var(--text-md)', marginBottom: 6 }}>Ready to join?</div>
                <p style={{ fontFamily: 'var(--font-body)', fontSize: 14, lineHeight: 1.6, color: 'var(--gray-300)', margin: '0 0 14px' }}>Membership is handled by The Hutchinson Bell national organization.</p>
                {Button && <Button size="sm" onClick={() => window.open(data.links.join, '_blank')} iconRight={<U.IconExternal />}>Join the Bell</Button>}
              </div>
            </div>
          </div>
        </U.Container>
      </U.Section>
    </React.Fragment>
  );
}

window.Pages = window.Pages || {};
window.Pages.contact = ContactPage;
