var React = window.React;
var { Button, Input, Select, Textarea } = window.NobleHealthDesignSystem_07bcfa;
var I = window.NobleIcons;

var track = function (event, params) {
  try { if (window.nhTrack) window.nhTrack(event, params); } catch (e) {}
};

var digits = (v) => String(v || '').replace(/\D/g, '');

/* ---------- referral form ----------
 * Email-only by design (confirmed 2026-08-02): these are referrals toward partner
 * providers, not Noble Health care requests, so they deliberately do NOT create
 * AxisCare leads — same reasoning as the newsletter. Delivery is the existing
 * Workspace SMTP via /api/partner-referral. */
var ROLES = ['Family member', 'Discharge planner / case manager', 'Social worker', "Physician's office", 'Other'];
var TIMEFRAMES = ['Immediately', 'Within a week', 'Within a month', 'Just exploring'];

function PartnerReferralForm({ doc }) {
  var [form, setForm] = React.useState({ name: '', phone: '', email: '', role: '', area: '', timeframe: '', notes: '', company: '' });
  var [errors, setErrors] = React.useState({});
  var [status, setStatus] = React.useState('idle'); // idle | sending | done | failed

  var set = (k) => (e) => {
    var v = e && e.target ? e.target.value : e;
    setForm((f) => Object.assign({}, f, { [k]: v }));
    setErrors((x) => (x[k] ? Object.assign({}, x, { [k]: null }) : x));
  };

  var validate = () => {
    var e = {};
    if (!form.name.trim()) e.name = 'Please tell us your name.';
    if (digits(form.phone).length < 10) e.phone = 'Please enter a 10-digit phone number.';
    if (form.email.trim() && !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(form.email.trim())) e.email = 'Please enter a valid email address.';
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  var submit = async (ev) => {
    ev.preventDefault();
    if (status === 'sending') return;
    if (!validate()) return;
    setStatus('sending');
    try {
      var res = await fetch('/api/partner-referral', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          service: doc.title,
          name: form.name.trim(),
          phone: form.phone.trim(),
          email: form.email.trim(),
          role: form.role,
          area: form.area.trim(),
          timeframe: form.timeframe,
          notes: form.notes.trim(),
          company: form.company, // honeypot
        }),
      });
      if (!res.ok) throw new Error('send failed');
      setStatus('done');
      track('funnel_step', { step: 'partner_referral_complete' });
    } catch (err) {
      setStatus('failed');
    }
  };

  if (status === 'done') {
    return (
      <div style={{ textAlign: 'center', padding: '40px 16px' }}>
        <span style={{ width: 56, height: 56, borderRadius: '50%', background: 'var(--green-600)', color: '#fff', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 18 }}>
          <I.Check width={26} height={26} />
        </span>
        <h3 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 24, color: 'var(--navy-900)', margin: '0 0 10px' }}>Thank you. We’ve got it.</h3>
        <p style={{ margin: 0, fontSize: 15, lineHeight: 1.6, color: 'var(--text-muted)' }}>
          A care coordinator will reach out about {doc.title.toLowerCase()} options within one business day.
        </p>
      </div>
    );
  }

  return (
    <form onSubmit={submit} noValidate style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      {status === 'failed' && (
        <p role="alert" style={{ margin: 0, padding: '12px 16px', borderRadius: 12, background: 'var(--warning-bg)', color: 'var(--warning-fg)', fontSize: 13.5, lineHeight: 1.5 }}>
          We couldn’t send that just now. Please try again in a moment.
        </p>
      )}
      {/* Honeypot: hidden from real people; bots fill it and the API quietly discards. */}
      <input type="text" name="company" tabIndex={-1} autoComplete="off" aria-hidden="true" value={form.company} onChange={set('company')}
        style={{ position: 'absolute', left: -9999, width: 1, height: 1, opacity: 0 }} />

      <Input label="Your name" placeholder="Jane Smith" required aria-required="true" aria-invalid={errors.name ? 'true' : 'false'} value={form.name} onChange={set('name')} error={errors.name} />
      <div className="nh-field-pair" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
        <Input label="Phone" type="tel" placeholder="(713) 000-0000" required aria-required="true" aria-invalid={errors.phone ? 'true' : 'false'} value={form.phone} onChange={set('phone')} error={errors.phone} />
        <Input label="Email" type="email" placeholder="Optional" aria-invalid={errors.email ? 'true' : 'false'} value={form.email} onChange={set('email')} error={errors.email} />
      </div>
      <Select label="Your role" placeholder="Choose one" options={ROLES} value={form.role} onChange={set('role')} />
      <Input label="Service" value={doc.title} readOnly aria-readonly="true" />
      <div className="nh-field-pair" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
        <Input label="City or ZIP" placeholder="Katy, 77450…" value={form.area} onChange={set('area')} />
        <Select label="Timeframe" placeholder="Choose one" options={TIMEFRAMES} value={form.timeframe} onChange={set('timeframe')} />
      </div>
      <Textarea
        label="Anything else we should know?"
        hint="General situation only. No medical records or diagnoses needed."
        placeholder="e.g. Mom is coming home from Memorial Hermann next week and the family needs options"
        rows={3}
        value={form.notes}
        onChange={set('notes')}
      />
      <Button type="submit" variant="secondary" size="lg" fullWidth disabled={status === 'sending'}>
        {status === 'sending' ? 'Sending…' : 'Request a call back'}
      </Button>
      <p style={{ margin: 0, textAlign: 'center', fontSize: 12, color: 'var(--text-muted)' }}>
        We’ll only use this to reach you about {doc.title.toLowerCase()} options. Never shared, never sold.
      </p>
    </form>
  );
}

/* ---------- page ---------- */
function PartnerPage({ slug, onNav, go }) {
  var doc = (window.NoblePartners || {})[slug];

  React.useEffect(() => {
    track('nav_click', { location: 'partner_' + String(slug || '').replace(/-/g, '_') });
  }, [slug]);

  if (!doc) {
    return (
      <main id="nh-main" tabIndex={-1} style={{ background: 'var(--surface-page)', minHeight: 460, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 'var(--space-16) var(--space-8)' }}>
        <div style={{ textAlign: 'center' }}>
          <h1 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 'var(--text-3xl)', color: 'var(--navy-900)', margin: 0 }}>Page not found</h1>
          <p style={{ color: 'var(--text-muted)', margin: '12px 0 24px' }}>That page doesn’t exist.</p>
          <Button onClick={() => onNav('home')}>Back to home</Button>
        </div>
      </main>
    );
  }

  return (
    <main id="nh-main" tabIndex={-1} style={{ background: 'var(--surface-page)' }}>
      {/* ---- header band ---- */}
      <section style={{ borderBottom: '1px solid var(--border-subtle)' }}>
        <div className="nh-shell" style={{ maxWidth: 'var(--container-xl)', margin: '0 auto', padding: '72px var(--space-8) 56px' }}>
          <div style={{ fontSize: 12, fontWeight: 800, letterSpacing: '0.28em', textTransform: 'uppercase', color: 'var(--green-700)', marginBottom: 16 }}>{doc.eyebrow}</div>
          <h1 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 'clamp(38px, 4.6vw, 64px)', lineHeight: 1.04, letterSpacing: '-0.015em', color: 'var(--navy-900)', margin: 0, textWrap: 'balance' }}>
            {doc.title}, <span style={{ fontStyle: 'italic', fontWeight: 500, color: 'var(--green-700)' }}>{doc.accent}.</span>
          </h1>
          <p style={{ margin: '22px 0 0', maxWidth: 620, fontSize: 18, lineHeight: 1.65, color: 'var(--sand-700)' }}>{doc.summary}</p>
        </div>
      </section>

      {/* ---- body: info left, form right ---- */}
      <section style={{ padding: '64px 0 88px' }}>
        <div className="nh-shell nh-partner-body" style={{ maxWidth: 'var(--container-xl)', margin: '0 auto', padding: '0 var(--space-8)', display: 'grid', gridTemplateColumns: '1.1fr 0.9fr', gap: 64, alignItems: 'start' }}>
          <div>
            {doc.intro.map((p) => (
              <p key={p.slice(0, 24)} style={{ margin: '0 0 18px', fontSize: 16, lineHeight: 1.7, color: 'var(--text-body)' }}>{p}</p>
            ))}

            <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 26, color: 'var(--navy-900)', margin: '36px 0 18px' }}>
              How we help
            </h2>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              {doc.howWeHelp.map((item) => (
                <span key={item} style={{ display: 'flex', alignItems: 'flex-start', gap: 11, fontSize: 15, fontWeight: 600, color: 'var(--navy-800)', lineHeight: 1.5 }}>
                  <span style={{ width: 22, height: 22, borderRadius: '50%', background: 'var(--green-50)', color: 'var(--green-700)', display: 'flex', alignItems: 'center', justifyContent: 'center', flex: 'none', marginTop: 1 }}>
                    <I.Check width={12} height={12} />
                  </span>{item}
                </span>
              ))}
            </div>

            <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 26, color: 'var(--navy-900)', margin: '40px 0 20px' }}>
              How it works
            </h2>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
              {doc.steps.map((s, i) => (
                <div key={s[0]} style={{ display: 'flex', gap: 16, alignItems: 'flex-start' }}>
                  <span style={{ width: 30, height: 30, borderRadius: '50%', background: 'var(--green-600)', color: '#fff', fontWeight: 800, fontSize: 13, display: 'flex', alignItems: 'center', justifyContent: 'center', flex: 'none' }}>{i + 1}</span>
                  <span style={{ fontSize: 15, lineHeight: 1.6, color: 'var(--text-body)', paddingTop: 4 }}>
                    <b style={{ color: 'var(--navy-900)' }}>{s[0]}.</b> {s[1]}
                  </span>
                </div>
              ))}
            </div>

            {/* ---- partners ---- */}
            <div style={{ marginTop: 44, padding: '22px 26px', background: 'var(--surface-card)', border: '1px solid var(--border-subtle)', borderRadius: 16 }}>
              <div style={{ fontSize: 11.5, fontWeight: 800, letterSpacing: '0.22em', textTransform: 'uppercase', color: 'var(--green-700)', marginBottom: 10 }}>Our partner network</div>
              {doc.partners.length === 0 ? (
                <p style={{ margin: 0, fontSize: 14.5, lineHeight: 1.65, color: 'var(--text-muted)' }}>{doc.partnerNote}</p>
              ) : (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                  {doc.partners.map((p) => (
                    <div key={p.name}>
                      <span style={{ display: 'block', fontWeight: 800, fontSize: 15, color: 'var(--navy-900)' }}>{p.name}</span>
                      <span style={{ fontSize: 13.5, color: 'var(--text-muted)' }}>{p.blurb}</span>
                    </div>
                  ))}
                </div>
              )}
            </div>

            <p style={{ margin: '28px 0 0', fontSize: 14.5, lineHeight: 1.6, color: 'var(--text-muted)' }}>
              Looking for in-home caregiving instead?{' '}
              <a href="/request-care" onClick={(e) => { e.preventDefault(); track('cta_click', { location: 'services' }); go('/request-care'); }} style={{ fontWeight: 700, cursor: 'pointer' }}>
                Request care →
              </a>
            </p>
          </div>

          {/* ---- form rail ---- */}
          <div className="nh-partner-rail" style={{ position: 'sticky', top: 96 }}>
            <div style={{ background: 'var(--surface-card)', border: '1px solid var(--border-subtle)', borderRadius: 24, boxShadow: 'var(--shadow-lg)', padding: 32 }}>
              <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 24, color: 'var(--navy-900)', margin: '0 0 8px' }}>
                {doc.formHeading}
              </h2>
              <p style={{ margin: '0 0 22px', fontSize: 14, lineHeight: 1.6, color: 'var(--text-muted)' }}>{doc.formIntro}</p>
              <PartnerReferralForm doc={doc} />
            </div>
          </div>
        </div>
      </section>
    </main>
  );
}
window.PartnerPage = PartnerPage;
