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

/* Qualifying steps, in order. Values match the AxisCare mapping in /api/submit-form. */
var QUESTIONS = [
  {
    field: 'relationship',
    title: 'Who are you searching for care for?',
    options: [
      { value: 'parent', label: 'My parent' },
      { value: 'spouse', label: 'My spouse' },
      { value: 'myself', label: 'Myself' },
      { value: 'someone-else', label: 'Someone else' },
    ],
  },
  {
    field: 'urgency',
    title: 'How quickly do you need care?',
    options: [
      { value: 'immediately', label: 'Immediately' },
      { value: '7days', label: 'Within 7 days' },
      { value: '30days', label: 'Within 30 days' },
      { value: 'flexible', label: "I'm flexible" },
    ],
  },
  {
    field: 'hours',
    title: 'How many hours per week?',
    options: [
      { value: 'less10', label: 'Less than 10' },
      { value: '11-20', label: '11 – 20' },
      { value: '21-40', label: '21 – 40' },
      { value: '40plus', label: '40+' },
      { value: 'unsure', label: 'Not sure yet' },
    ],
  },
  {
    field: 'payment',
    title: 'How do you plan to pay?',
    options: [
      { value: 'personal funds', label: 'Personal funds' },
      { value: 'va', label: 'VA benefits' },
      { value: 'medicaid', label: 'Medicaid' },
      { value: 'insurance', label: 'Long-term care insurance' },
    ],
  },
];

var BEST_TIME = [
  { value: 'morning', label: 'Morning (8AM – 12PM)' },
  { value: 'afternoon', label: 'Afternoon (12PM – 5PM)' },
  { value: 'evening', label: 'Evening (5PM – 8PM)' },
  { value: 'anytime', label: 'Anytime' },
];
var CONTACT_METHOD = [
  { value: 'phone', label: 'Call' },
  { value: 'text', label: 'Text' },
  { value: 'email', label: 'Email' },
];

/* ---------- local hold-and-retry ----------
 * If the lead API is unreachable, the request is kept on the visitor's own device and
 * resubmitted on their next visit. Nothing is sent to any third party, and the entry
 * expires on its own so stale care requests are never submitted late.
 */
var PENDING_KEY = 'nh_pending_lead';
var PENDING_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
var PENDING_MAX_ATTEMPTS = 5;

function savePendingLead(payload) {
  try {
    var existing = readPendingLead();
    window.localStorage.setItem(PENDING_KEY, JSON.stringify({
      payload: payload,
      savedAt: (existing && existing.savedAt) || Date.now(),
      attempts: ((existing && existing.attempts) || 0) + 1,
    }));
  } catch (e) { /* private mode or storage full — the on-screen phone number still applies */ }
}

function readPendingLead() {
  try {
    var raw = window.localStorage.getItem(PENDING_KEY);
    if (!raw) return null;
    var entry = JSON.parse(raw);
    if (!entry || !entry.payload) return null;
    if (Date.now() - entry.savedAt > PENDING_TTL_MS || entry.attempts > PENDING_MAX_ATTEMPTS) {
      clearPendingLead();
      return null;
    }
    return entry;
  } catch (e) { return null; }
}

function clearPendingLead() {
  try { window.localStorage.removeItem(PENDING_KEY); } catch (e) { /* nothing to do */ }
}

/* ---------- handoff from the home page ----------
 * The hero starts the flow by capturing a ZIP. It stashes the validated ZIP and
 * resolved city here so this page opens on question 1 instead of asking again.
 * Read-once: consumed on mount so a later visit starts clean.
 */
function takeSeed() {
  try {
    var raw = window.sessionStorage.getItem('nh_seed');
    if (!raw) return null;
    window.sessionStorage.removeItem('nh_seed');
    var seed = JSON.parse(raw);
    return seed && seed.zipcode ? seed : null;
  } catch (e) { return null; }
}

var REASSURANCE = [
  { ic: 'Phone', t: 'A real person, fast', d: 'A care coordinator responds within one business hour — however you prefer.' },
  { ic: 'Shield', t: 'Licensed & insured', d: 'Every caregiver is background-checked and trained.' },
  { ic: 'Heart', t: 'No pressure, ever', d: 'We help you understand options at your own pace.' },
];

/* Selectable tile used for every qualifying question. */
function OptionTile({ label, selected, onClick }) {
  var [hover, setHover] = React.useState(false);
  return (
    <button
      type="button"
      aria-pressed={selected}
      onClick={onClick}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        padding: '16px 18px',
        borderRadius: 'var(--radius-md)',
        border: '1px solid ' + (selected ? 'var(--green-600)' : 'var(--border-default)'),
        background: selected ? 'var(--green-50)' : 'var(--surface-card)',
        color: selected ? 'var(--green-800)' : 'var(--text-body)',
        fontFamily: 'var(--font-body)',
        fontSize: 'var(--text-sm)',
        fontWeight: 'var(--fw-semibold)',
        textAlign: 'left',
        cursor: 'pointer',
        boxShadow: selected ? 'var(--shadow-sm)' : 'none',
        transform: hover && !selected ? 'translateY(-1px)' : 'none',
        transition: 'all var(--duration-fast) var(--ease-standard)',
      }}
    >
      {label}
    </button>
  );
}

function ProgressRail({ step, total }) {
  return (
    <div style={{ display: 'flex', gap: 6, marginBottom: 'var(--space-6)' }}>
      {Array.from({ length: total }).map((_, i) => (
        <span
          key={i}
          style={{
            height: 4,
            flex: 1,
            borderRadius: 'var(--radius-pill)',
            background: i < step ? 'var(--green-600)' : 'var(--sand-200)',
            transition: 'background var(--duration-base) var(--ease-standard)',
          }}
        />
      ))}
    </div>
  );
}

function StepHeading({ eyebrow, title }) {
  return (
    <div style={{ marginBottom: 'var(--space-5)' }}>
      {eyebrow && (
        <div style={{ fontSize: 'var(--text-2xs)', fontWeight: 800, letterSpacing: 'var(--tracking-caps)', textTransform: 'uppercase', color: 'var(--green-700)', marginBottom: 8 }}>
          {eyebrow}
        </div>
      )}
      <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 'var(--text-2xl)', lineHeight: 1.15, color: 'var(--navy-900)', margin: 0 }}>
        {title}
      </h2>
    </div>
  );
}

/* ---------- URL <-> step mapping ----------
 * Each step gets a real URL so page views show the funnel and the back button works.
 * Slugs are generic ("who", "when") — they never reveal a health condition, and the
 * visitor's answers are never placed in the URL.
 */
var STEP_SLUG = { 1: '', 2: 'who', 3: 'when', 4: 'hours', 5: 'payment', 6: 'matching', 7: 'contact', 8: 'thank-you' };
var SLUG_STEP = { '': 1, 'who': 2, 'when': 3, 'hours': 4, 'payment': 5, 'matching': 6, 'contact': 7, 'thank-you': 8 };
var BASE_PATH = '/request-care';

function pathForStep(n) {
  var slug = STEP_SLUG[n];
  return slug ? BASE_PATH + '/' + slug : BASE_PATH;
}
function stepFromPath(path) {
  var slug = String(path || '').replace(BASE_PATH, '').replace(/^\//, '').replace(/\/$/, '');
  return SLUG_STEP[slug] || 1;
}
/* Which answer each step requires before a later step may be shown. */
var STEP_REQUIRES = { 2: 'zipcode', 3: 'relationship', 4: 'urgency', 5: 'hours', 6: 'payment', 7: 'payment' };

function RequestCarePage({ onNav, path, go }) {
  var step = stepFromPath(path);
  var submitted = step === 8;
  var [loading, setLoading] = React.useState(false);
  var [zipError, setZipError] = React.useState('');
  var [formError, setFormError] = React.useState('');
  var [recovered, setRecovered] = React.useState(false);
  var [errors, setErrors] = React.useState({});

  /* Consumed once, on mount, so the ZIP entered in the hero carries through. */
  var seed = React.useMemo(takeSeed, []);
  var [locationText, setLocationText] = React.useState((seed && seed.locationText) || '');

  var [data, setData] = React.useState({
    zipcode: (seed && seed.zipcode) || '',
    relationship: '', urgency: '', hours: '', payment: '',
    contactName: '', contactPhone: '', contactEmail: '', careRecipientName: '',
    bestTime: '', contactMethod: '', additionalInfo: '', isSelf: false,
  });

  var set = (field, value) => setData((prev) => ({ ...prev, [field]: value }));

  /* Navigation now goes through the URL, so back/forward move through the funnel. */
  var setStep = (n, opts) => go(pathForStep(n), opts);
  var setSubmitted = () => go(pathForStep(8));

  /* Analytics. Only step names are ever passed — never the visitor's answers. */
  var track = (event, params) => {
    try { if (window.nhTrack) window.nhTrack(event, params); } catch (e) { /* never break the form */ }
  };

  React.useEffect(() => { track('request_care_opened'); }, []);

  /* Someone deep-linking or going "forward" into a later step without having answered
   * the earlier ones would otherwise submit an incomplete lead. Send them to the start.
   * replace: true so it doesn't add a dead history entry they'd have to click past. */
  React.useEffect(() => {
    var required = STEP_REQUIRES[step];
    if (required && !data[required]) setStep(1, { replace: true });
  }, [step]);

  /* Coarse location for "care near you" copy. Fails silently — never blocks the form.
   * Only fills a gap: a ZIP the visitor actually typed always beats an IP guess, so
   * this never overwrites a location we already have. */
  React.useEffect(() => {
    var cancelled = false;
    fetch('/api/get-location-data')
      .then((r) => (r.ok ? r.json() : null))
      .then((d) => {
        if (cancelled || !d || !d.derivedLocationString || d.derivedLocationString === 'your area') return;
        setLocationText((prev) => prev || d.derivedLocationString);
      })
      .catch(() => {});
    return () => { cancelled = true; };
  }, []);

  /* Step 6 is a brief "searching" beat before we ask for contact details.
   * It advances with replace: true so it leaves no history entry — otherwise pressing
   * Back from the contact step would land here and immediately bounce forward again. */
  React.useEffect(() => {
    if (step !== 6) return;
    var t = setTimeout(() => {
      track('funnel_step', { step: 'contact_details_reached', step_index: 6 });
      setStep(7, { replace: true });
    }, 2200);
    return () => clearTimeout(t);
  }, [step]);

  /* A lead held from a previous visit (lead API was down) is resubmitted quietly here. */
  React.useEffect(() => {
    var entry = readPendingLead();
    if (!entry) return;
    var cancelled = false;
    fetch('/api/submit-form', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(entry.payload),
    })
      .then((res) => {
        if (cancelled) return;
        if (res.ok) {
          clearPendingLead();
          track('lead_submitted', { step: 'recovered' }); // a lead saved from an outage
          setRecovered(true);
        } else {
          // Count the attempt so it eventually gives up rather than retrying forever.
          savePendingLead(entry.payload);
        }
      })
      .catch(() => { if (!cancelled) savePendingLead(entry.payload); });
    return () => { cancelled = true; };
  }, []);

  var submitZip = async (e) => {
    e.preventDefault();
    var zip = data.zipcode.trim();
    if (!/^\d{5}$/.test(zip)) { setZipError('Please enter a valid 5-digit ZIP code.'); return; }
    setZipError('');
    setLoading(true);
    try {
      var res = await fetch('https://api.zippopotam.us/us/' + zip);
      if (!res.ok) throw new Error('not found');
      var place = (await res.json()).places[0];
      setLocationText(place['place name'] + ', ' + place['state abbreviation']);
      track('funnel_step', { step: 'zip_submitted', step_index: 1 });
      setStep(2);
    } catch (err) {
      setZipError("We couldn't find that ZIP code. Please check and try again.");
    } finally {
      setLoading(false);
    }
  };

  var validateContact = () => {
    var next = {};
    if (!data.contactName.trim() || data.contactName.trim().length < 2) next.contactName = 'Please enter your name.';
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(data.contactEmail)) next.contactEmail = 'Please enter a valid email address.';
    if (data.contactPhone.replace(/\D/g, '').length < 10) next.contactPhone = 'Please enter a 10-digit phone number.';
    if (!data.isSelf && !data.careRecipientName.trim()) next.careRecipientName = "Please enter the name of the person needing care.";
    if (!data.bestTime) next.bestTime = 'Please choose a best time.';
    if (!data.contactMethod) next.contactMethod = 'Please choose a contact method.';
    setErrors(next);
    return Object.keys(next).length === 0;
  };

  var buildPayload = () => ({
    ...data,
    careRecipientName: data.isSelf ? data.contactName : data.careRecipientName,
    formName: 'Multi-Step Hero Form',
    locationText: locationText,
  });

  /* Posts a lead. Resolves true on success; throws with .retryable on failure. */
  var postLead = async (payload) => {
    var res = await fetch('/api/submit-form', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload),
    });
    if (!res.ok) {
      var body = await res.json().catch(() => null);
      var err = new Error((body && body.error) || '');
      err.retryable = !body || body.retryable !== false;
      throw err;
    }
    return true;
  };

  var submitAll = async (e) => {
    e.preventDefault();
    setFormError('');
    if (!validateContact()) return;
    setLoading(true);
    var payload = buildPayload();
    try {
      await postLead(payload);
      clearPendingLead();
      track('lead_submitted', { step: 'complete' }); // conversion — no parameters about the person
      setSubmitted(true);
      window.scrollTo({ top: 0 });
    } catch (err) {
      // Hold the lead on this device so an AxisCare outage doesn't lose it — it is
      // resubmitted automatically the next time this visitor loads the site.
      if (err.retryable) savePendingLead(payload);
      track('lead_failed', { outcome: err.retryable ? 'held_for_retry' : 'rejected' });
      setFormError(err.message || "We couldn't send your request just now. We've saved it on this device and will keep trying automatically.");
    } finally {
      setLoading(false);
    }
  };

  /* ---------- confirmation ---------- */
  if (submitted) {
    return (
      <main style={{ background: 'var(--surface-page)', minHeight: 600, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 'var(--space-16) var(--space-8)' }}>
        <Card padding="lg" elevated style={{ maxWidth: 520, textAlign: 'center' }}>
          <span style={{ display: 'inline-flex', width: 72, height: 72, borderRadius: '50%', background: 'var(--green-100)', color: 'var(--green-700)', alignItems: 'center', justifyContent: 'center', marginBottom: 20 }}>
            <I.Check width={36} height={36} />
          </span>
          <h1 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 'var(--text-3xl)', color: 'var(--navy-900)', margin: 0 }}>We've got your request</h1>
          <p style={{ fontSize: 'var(--text-lg)', color: 'var(--text-muted)', margin: '12px 0 24px', lineHeight: 1.6 }}>
            A care coordinator will reach out within one business hour, using the contact method you chose.
          </p>
          <Button size="lg" onClick={() => onNav('home')}>Back to home</Button>
        </Card>
      </main>
    );
  }

  /* ---------- step body ---------- */
  var body;
  if (step === 1) {
    body = (
      <form onSubmit={submitZip}>
        <StepHeading eyebrow="Step 1 of 6" title="Let's start with your ZIP code" />
        <p style={{ fontSize: 'var(--text-sm)', color: 'var(--text-muted)', margin: '0 0 var(--space-5)', lineHeight: 1.6 }}>
          We'll match you with in-home care options available in your area.
        </p>
        <Input
          label="ZIP code"
          placeholder="77024"
          inputMode="numeric"
          maxLength={5}
          required
          value={data.zipcode}
          error={zipError || undefined}
          onChange={(e) => { set('zipcode', e.target.value.replace(/\D/g, '')); if (zipError) setZipError(''); }}
        />
        <Button type="submit" size="lg" fullWidth disabled={loading} style={{ marginTop: 'var(--space-5)' }} iconRight={!loading ? <I.ArrowRight width={18} height={18} /> : null}>
          {loading ? 'Checking…' : 'Continue'}
        </Button>
      </form>
    );
  } else if (step >= 2 && step <= 5) {
    var q = QUESTIONS[step - 2];
    body = (
      <div>
        <StepHeading eyebrow={'Step ' + step + ' of 6'} title={q.title} />
        <div className="nh-options" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-3)' }}>
          {q.options.map((o) => (
            <OptionTile key={o.value} label={o.label} selected={data[q.field] === o.value} onClick={() => set(q.field, o.value)} />
          ))}
        </div>
        <div style={{ display: 'flex', gap: 'var(--space-3)', marginTop: 'var(--space-6)' }}>
          <Button variant="outline" onClick={() => setStep(step - 1)}>Back</Button>
          <Button
            style={{ flex: 1 }}
            disabled={!data[q.field]}
            onClick={() => {
              // The question that was answered — never which answer was chosen.
              track('funnel_step', { step: q.field, step_index: step });
              setStep(step === 5 ? 6 : step + 1);
            }}
            iconRight={<I.ArrowRight width={18} height={18} />}
          >
            Continue
          </Button>
        </div>
      </div>
    );
  } else if (step === 6) {
    body = (
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 18, padding: 'var(--space-16) 0' }} role="status" aria-live="polite">
        <span style={{ width: 44, height: 44, borderRadius: '50%', border: '3px solid var(--green-100)', borderTopColor: 'var(--green-600)', animation: 'nh-spin 900ms linear infinite' }} />
        <p style={{ fontSize: 'var(--text-md)', color: 'var(--text-muted)', margin: 0 }}>
          Finding care options{locationText ? ' near ' + locationText : ' in your area'}…
        </p>
      </div>
    );
  } else {
    body = (
      <form onSubmit={submitAll} style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-5)' }}>
        <StepHeading eyebrow="Last step" title="How should we reach you?" />
        <div className="nh-field-pair" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-4)' }}>
          <Input label="Your name" placeholder="Jane Doe" required value={data.contactName} error={errors.contactName} onChange={(e) => set('contactName', e.target.value)} />
          <Input label="Phone" type="tel" placeholder="(555) 123-4567" required value={data.contactPhone} error={errors.contactPhone} onChange={(e) => set('contactPhone', e.target.value)} />
        </div>
        <Input label="Email" type="email" placeholder="jane@email.com" required value={data.contactEmail} error={errors.contactEmail} leftIcon={<I.Mail width={16} height={16} />} onChange={(e) => set('contactEmail', e.target.value)} />
        <Input
          label="Who needs care?"
          placeholder="Name of the person needing care"
          required={!data.isSelf}
          disabled={data.isSelf}
          value={data.isSelf ? data.contactName : data.careRecipientName}
          error={errors.careRecipientName}
          onChange={(e) => set('careRecipientName', e.target.value)}
        />
        <Checkbox label="Care is for me" checked={data.isSelf} onChange={(e) => set('isSelf', e.target.checked)} />
        <div className="nh-field-pair" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-4)' }}>
          <Select label="Best time to reach you" placeholder="Select" required options={BEST_TIME} value={data.bestTime} error={errors.bestTime} onChange={(e) => set('bestTime', e.target.value)} />
          <Select label="Preferred contact method" placeholder="Select" required options={CONTACT_METHOD} value={data.contactMethod} error={errors.contactMethod} onChange={(e) => set('contactMethod', e.target.value)} />
        </div>
        <Textarea label="Anything we should know?" rows={3} placeholder="Daily routine, medications, preferences, or questions…" value={data.additionalInfo} onChange={(e) => set('additionalInfo', e.target.value)} />
        {formError && (
          <div role="alert" style={{ background: 'var(--danger-bg)', color: 'var(--danger-fg)', borderRadius: 'var(--radius-md)', padding: '12px 14px', fontSize: 'var(--text-sm)', lineHeight: 1.5 }}>
            <div>{formError}</div>
            <div style={{ marginTop: 6 }}>
              We've saved your answers on this device and will keep trying, so nothing is lost.
            </div>
          </div>
        )}
        <div style={{ display: 'flex', gap: 'var(--space-3)' }}>
          <Button variant="outline" type="button" onClick={() => setStep(5)}>Back</Button>
          <Button type="submit" size="lg" style={{ flex: 1 }} disabled={loading}>
            {loading ? 'Sending…' : 'Request my free consultation'}
          </Button>
        </div>
        <p style={{ fontSize: 'var(--text-xs)', color: 'var(--text-subtle)', textAlign: 'center', margin: 0, lineHeight: 1.5 }}>
          By submitting, you agree to be contacted about care services. We never sell your information.
        </p>
      </form>
    );
  }

  return (
    <main style={{ background: 'var(--surface-page)' }}>
      <div className="nh-request nh-section" style={{ maxWidth: 'var(--container-lg)', margin: '0 auto', padding: 'var(--space-12) var(--space-8) var(--space-20)', display: 'grid', gridTemplateColumns: '1fr 1.15fr', gap: 'var(--space-12)', alignItems: 'start' }}>
        {/* Left — reassurance */}
        <div className="nh-reassure" style={{ position: 'sticky', top: 100 }}>
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, fontSize: 'var(--text-2xs)', fontWeight: 800, letterSpacing: 'var(--tracking-caps)', textTransform: 'uppercase', color: 'var(--green-700)' }}>
            <span style={{ width: 20, height: 2, background: 'var(--green-500)', borderRadius: 2 }} />Request care
          </div>
          <h1 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 'var(--text-4xl)', lineHeight: 1.08, color: 'var(--navy-900)', margin: '14px 0 0' }}>
            Let's find the right care
          </h1>
          <p style={{ fontSize: 'var(--text-lg)', color: 'var(--text-muted)', margin: '16px 0 28px', lineHeight: 1.6 }}>
            A few quick questions{locationText ? ' about care in ' + locationText : ''} — then we'll be in touch within the hour, free and with no obligation.
          </p>
          {REASSURANCE.map((r) => {
            var Ic = I[r.ic];
            return (
              <div key={r.t} style={{ display: 'flex', gap: 14, marginBottom: 18 }}>
                <span style={{ flex: '0 0 auto', width: 44, height: 44, borderRadius: 'var(--radius-md)', background: 'var(--green-50)', color: 'var(--green-700)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <Ic width={22} height={22} />
                </span>
                <div>
                  <div style={{ fontWeight: 700, color: 'var(--navy-900)', fontSize: 'var(--text-md)' }}>{r.t}</div>
                  <div style={{ fontSize: 'var(--text-sm)', color: 'var(--text-muted)', lineHeight: 1.5 }}>{r.d}</div>
                </div>
              </div>
            );
          })}
        </div>

        {/* Right — the flow */}
        <Card padding="lg" elevated>
          {recovered && (
            <div role="status" style={{ display: 'flex', alignItems: 'flex-start', gap: 10, background: 'var(--success-bg)', color: 'var(--success-fg)', borderRadius: 'var(--radius-md)', padding: '12px 14px', marginBottom: 'var(--space-5)', fontSize: 'var(--text-sm)', lineHeight: 1.5 }}>
              <I.Check width={18} height={18} style={{ flex: '0 0 auto', marginTop: 2 }} />
              <span>Your earlier request has now reached our care team — no need to fill this out again.</span>
            </div>
          )}
          {step !== 6 && <ProgressRail step={Math.min(step, 6)} total={6} />}
          {body}
        </Card>
      </div>
    </main>
  );
}
window.RequestCarePage = RequestCarePage;
