// signup.jsx — Renegade address/NMI-first signup wizard
const { useState: sUseState, useEffect: sUseEffect, useRef: sUseRef } = React;

const STEPS = ['Address', 'Your plan', 'Your details', 'Review'];

const Stepper = ({ step }) => (
  <div className="stepper" aria-label="Signup progress">
    {STEPS.flatMap((s, i) => [
      i > 0 ? <div key={'l' + i} className={'line' + (i <= step ? ' done' : '')} /> : null,
      <div key={'s' + i} className={'stp ' + (i < step ? 'done' : i === step ? 'current' : '')}>
        <div className="dot">{i < step ? <Icon n="check" size={18} /> : i + 1}</div>
        <div className="lab">{s}</div>
      </div>,
    ])}
  </div>
);

/* sample address suggestions */
const ADDR_SUGGEST = [
  { line: '14 Carrington Rd, Marrickville', sub: 'NSW 2204', distributor: 'Ausgrid', solar: false },
  { line: '8/22 Marion St, Leichhardt', sub: 'NSW 2040', distributor: 'Ausgrid', solar: false },
  { line: '47 Latrobe Tce, Paddington', sub: 'QLD 4064', distributor: 'Energex', solar: true },
  { line: '3 Beaumont St, Hamilton', sub: 'NSW 2303', distributor: 'Essential Energy', solar: false },
  { line: '120 Given Tce, Rosalie', sub: 'QLD 4064', distributor: 'Energex', solar: false },
];

/* ---------------- Step 1: lookup ---------------- */
const LookupStep = ({ initMode, initValue, onFound }) => {
  const [query, setQuery] = sUseState(initValue || '');
  const [openAc, setOpenAc] = sUseState(false);
  const [nmiState, setNmiState] = sUseState('idle'); // idle | checking | valid | error
  const [searching, setSearching] = sUseState(false);
  const digitsOnly = /^\d+$/.test(query.trim());
  const looksNmi = digitsOnly && query.trim().length >= 6;
  const nmi = query.replace(/\s/g, '');

  const matches = ADDR_SUGGEST.filter(a => !looksNmi && query.length >= 2 && (a.line + ' ' + a.sub).toLowerCase().includes(query.toLowerCase()));
  const showAc = openAc && !looksNmi && query.length >= 2 && matches.length > 0;

  const pickAddress = (a) => {
    setQuery(a.line + ', ' + a.sub); setOpenAc(false); setSearching(true);
    setTimeout(() => { setSearching(false); onFound({ address: a.line + ', ' + a.sub, distributor: a.distributor, solar: a.solar }); }, 950);
  };

  // NMI validation, inferred from a numeric query.
  sUseEffect(() => {
    if (!looksNmi) { setNmiState('idle'); return; }
    if (!/^\d*$/.test(nmi)) { setNmiState('error'); return; }
    if (nmi.length < 10) { setNmiState('idle'); return; }
    if (nmi.length > 11) { setNmiState('error'); return; }
    setNmiState('checking');
    const t = setTimeout(() => setNmiState('valid'), 1100);
    return () => clearTimeout(t);
  }, [nmi, looksNmi]);

  const submitNmi = () => {
    if (nmiState !== 'valid') return;
    // last digit even => has solar (demo determinism)
    const solar = Number(nmi[nmi.length - 1]) % 2 === 0;
    onFound({ address: '14 Carrington Rd, Marrickville, NSW 2204', distributor: 'Ausgrid', solar, nmi });
  };

  return (
    <div className="flow-card">
      <div className="flow-head">
        <h2>Let's find your connection</h2>
        <p>Enter your address or NMI. We'll pull your meter and distributor — no bill upload needed.</p>
      </div>
      <div className="card card-outline">
        <div className="ac">
          <Field
            label="Supply address or NMI"
            icon={looksNmi ? 'hash' : 'mapPin'}
            placeholder="Start typing your address or enter a 10/11-digit NMI"
            value={query}
            autoComplete="off"
            inputMode="text"
            maxLength={looksNmi ? 11 : undefined}
            valid={nmiState === 'valid'}
            error={nmiState === 'error' ? (/[^\d]/.test(nmi) ? 'NMI should contain digits only.' : 'A NMI is usually 10 or 11 digits.') : null}
            onChange={e => { setQuery(e.target.value); setOpenAc(true); }}
            onFocus={() => setOpenAc(true)}
            hint={searching ? null : looksNmi ? 'Looks like an NMI — we’ll validate your meter directly.' : 'We only need where the power is connected.'} />
          {searching && <div className="field-hint" style={{ display: 'flex', alignItems: 'center', gap: 8 }}><Spinner /> Looking up your property…</div>}
          {nmiState === 'checking' && <div className="field-hint" style={{ display: 'flex', alignItems: 'center', gap: 8 }}><Spinner /> Validating with the metering registry…</div>}
          {nmiState === 'valid' && <div className="field-hint" style={{ color: 'var(--delta-positive)', display: 'flex', alignItems: 'center', gap: 6 }}><Icon n="checkCircle" size={15} /> Valid NMI — Ausgrid network, NSW.</div>}
          {showAc && (
            <div className="ac-menu" role="listbox">
              {matches.map((a, i) => (
                <div className="ac-item" role="option" key={i} onClick={() => pickAddress(a)}>
                  <Icon n="mapPin" size={18} />
                  <div><div>{a.line}</div><div className="sub">{a.sub} · {a.distributor}</div></div>
                </div>
              ))}
            </div>
          )}
          {query.length >= 2 && !looksNmi && matches.length === 0 && !searching && (
            <div className="field-hint">No address match yet — keep typing, or enter your NMI.</div>
          )}
          <div style={{ marginTop: 18 }}>
            <Button variant="primary" size="lg" className="btn-block" disabled={looksNmi ? nmiState !== 'valid' : query.length < 2} onClick={looksNmi ? submitNmi : () => matches[0] && pickAddress(matches[0])}>
              Find my property <Icon n="arrowRight" size={18} />
            </Button>
          </div>
        </div>
      </div>
      <p style={{ textAlign: 'center', fontSize: 12.5, color: 'var(--fg-3)', marginTop: 18 }}>
        Tip — enter an address suggestion or a 10/11-digit NMI. Use a NMI ending in an even digit to see the solar path.
      </p>
    </div>
  );
};

const Spinner = ({ on }) => (
  <span style={{ display: 'inline-block', width: 15, height: 15, border: '2px solid ' + (on === 'dark' ? 'rgba(255,255,255,0.3)' : 'var(--border-strong)'), borderTopColor: 'var(--accent)', borderRadius: '50%', animation: 'rngspin 0.7s linear infinite' }} />
);
window.Spinner = Spinner;

/* ---------------- Step 2: property + plan ---------------- */
const PlanCard = ({ plan, distributor, selected, onSelect, recommended }) => {
  const d = DISTRIBUTORS[distributor] || { region: 'NSW', ref: 1828 };
  const monthly = plan.yearly / 12;
  return (
    <div className={'plan' + (selected ? ' is-selected' : '')}>
      <div className="plan-top">
        {recommended && <div className="plan-flag accent"><Icon n="check" size={13} /> Best match for this home</div>}
        {plan.forSolar && <div className="plan-flag"><Icon n="sun" size={13} /> Solar home plan</div>}
        <h3>{plan.name}</h3>
        <p className="plan-desc">{plan.desc}</p>
      </div>
      <div className="plan-meta">
        <div className="mrow"><Icon n="meter" size={17} /><span><b>Meter:</b> {plan.meterType}</span></div>
        <div className="mrow"><Icon n="info" size={17} /><span><b>Network:</b> {d.region} · {distributor}</span></div>
        <div className="mrow"><Icon n="clock" size={17} /><span><b>Term:</b> 12-month rate guarantee, no lock-in</span></div>
      </div>
      <div className="plan-price">
        <div>
          <div className="ref"><Icon n="trendDown" size={15} /> {plan.refPct}% below the reference price</div>
          <div className="amt tnum" style={{ marginTop: 8 }}>{fmt$0(monthly)}<span className="per"> /mo est.</span></div>
          <div className="yr tnum">{fmt$0(plan.yearly)}/yr · based on 3,900 kWh average use</div>
        </div>
      </div>
      <div className="plan-actions">
        <Button variant={selected ? 'navy' : 'primary'} size="lg" className="btn-block" onClick={onSelect}>
          {selected ? (<><Icon n="check" size={18} /> Selected</>) : 'Choose this plan'}
        </Button>
        <div className="plan-foot">
          Code {plan.code}. Estimate includes GST and assumes typical use; your bill depends on actual consumption. <a>Basic Plan Information →</a>
        </div>
      </div>
    </div>
  );
};

const PropertyPlanStep = ({ property, setProperty, solarGate, selectedPlan, setSelectedPlan, onContinue }) => {
  const { address, distributor, solar } = property;
  const d = DISTRIBUTORS[distributor] || { region: 'NSW' };
  const eligible = solar ? [PLANS.solar] : [PLANS.tou, PLANS.home];
  const gated = solar && solarGate === 'gate';

  sUseEffect(() => {
    // default-select recommended plan when list changes
    if (gated) return;
    if (!eligible.find(p => p.id === selectedPlan)) setSelectedPlan(eligible[0].id);
  }, [solar, solarGate]);

  return (
    <div className="flow-card" style={{ maxWidth: solar ? 720 : 900 }}>
      <div className="flow-head">
        <h2>We found your property</h2>
        <p>Confirm the details below, then pick your plan.</p>
      </div>

      {/* property card */}
      <div className="prop">
        <div className="prop-head">
          <div className="prop-ico"><Icon n="home" size={24} /></div>
          <div style={{ flex: 1 }}>
            <div style={{ fontWeight: 700, fontSize: 16 }}>{address}</div>
            <div style={{ fontSize: 13.5, color: 'var(--fg-3)', marginTop: 2 }}>{d.region} · {distributor} network</div>
          </div>
          <a style={{ fontSize: 13, color: 'var(--support)', cursor: 'pointer', borderBottom: '1px solid currentColor' }} onClick={() => setProperty(null)}>Not right?</a>
        </div>
        <div className="prop-tags">
          <Tag icon="user">Residential</Tag>
          <Tag icon="meter">Smart meter (Type 4)</Tag>
          <Tag icon="plug">Single-phase</Tag>
          <Tag icon="info">No controlled load</Tag>
          {solar
            ? <Tag kind="solar" icon="sun">Rooftop solar detected</Tag>
            : <Tag kind="good" icon="check">No rooftop solar — you're eligible</Tag>}
        </div>
        {/* demo solar toggle */}
        <div style={{ marginTop: 16, paddingTop: 16, borderTop: '1px dashed var(--border-light)', display: 'flex', alignItems: 'center', gap: 10, fontSize: 12.5, color: 'var(--fg-3)' }}>
          <Icon n="sliders" size={15} />
          <span>Demo — simulate this home's solar status:</span>
          <button className="segmented" style={{ marginLeft: 'auto' }} aria-hidden="true" tabIndex={-1} onClick={e => e.preventDefault()}>
            <span style={{ padding: 0, display: 'flex', gap: 3 }}>
              <span role="button" tabIndex={0} className={'seg-mini'} onClick={() => setProperty({ ...property, solar: false })} style={segMini(!solar)}>No solar</span>
              <span role="button" tabIndex={0} className={'seg-mini'} onClick={() => setProperty({ ...property, solar: true })} style={segMini(solar)}>Has solar</span>
            </span>
          </button>
        </div>
      </div>

      {/* gate or plans */}
      {gated ? (
        <div className="card card-outline" style={{ marginTop: 24 }}>
          <div className="gate">
            <div className="gico"><Icon n="sun" size={34} /></div>
            <h3 style={{ fontSize: 26 }}>This home has solar — we're not your retailer.</h3>
            <p style={{ marginTop: 14 }}>Renegade exists so non-solar homes stop subsidising solar exporters. Signing up solar homes on standard rates would re-create the exact problem we're fighting. So we'll be straight with you: we're not the cheapest deal for an exporting home today.</p>
            <p style={{ marginTop: 12 }}>If you'd still like a cost-reflective solar plan with no cross-subsidy, join the waitlist for <b>Responsible Solar Citizen</b>.</p>
            <div style={{ display: 'flex', gap: 12, justifyContent: 'center', marginTop: 24, flexWrap: 'wrap' }}>
              <Button variant="primary" size="lg">Join the solar waitlist</Button>
              <Button variant="secondary" size="lg" onClick={() => setProperty({ ...property, solar: false })}>This home has no solar</Button>
            </div>
          </div>
        </div>
      ) : (
        <div style={{ display: 'contents' }}>
          {solar && (
            <div className="banner banner-warn" style={{ marginTop: 24 }}>
              <Icon n="sun" size={20} />
              <div>This home has rooftop solar, so you're on our <b>cost-reflective</b> solar plan. The midday feed-in is zero-to-negative on purpose — that's how we keep non-solar customers from subsidising the midday export glut.</div>
            </div>
          )}
          <div className={solar ? '' : 'grid-2'} style={{ marginTop: 24, gridTemplateColumns: solar ? undefined : '1fr 1fr' }}>
            {eligible.map((p, i) => (
              <PlanCard key={p.id} plan={p} distributor={distributor}
                recommended={!solar && i === 0}
                selected={selectedPlan === p.id} onSelect={() => setSelectedPlan(p.id)} />
            ))}
          </div>
          <div className="flow-nav">
            <span style={{ fontSize: 13, color: 'var(--fg-3)', display: 'flex', alignItems: 'center', gap: 6 }}><Icon n="lock" size={14} /> Your details are encrypted and never sold.</span>
            <Button variant="primary" size="lg" onClick={onContinue}>Get started <Icon n="arrowRight" size={18} /></Button>
          </div>
        </div>
      )}
    </div>
  );
};
const segMini = (active) => ({ padding: '7px 12px', borderRadius: 4, fontSize: 12.5, fontWeight: 600, cursor: 'pointer', background: active ? '#fff' : 'transparent', color: active ? 'var(--fg-1)' : 'var(--fg-3)', boxShadow: active ? 'var(--shadow-sm)' : 'none' });

/* ---------------- Step 3: details ---------------- */
const DetailsStep = ({ form, setForm, onBack, onContinue }) => {
  const [touched, setTouched] = sUseState(false);
  const set = (k) => (e) => setForm({ ...form, [k]: e.target.value });
  const errs = {
    first: !form.first ? 'Enter your first name.' : null,
    last: !form.last ? 'Enter your last name.' : null,
    email: !form.email ? 'Enter your email.' : !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(form.email) ? 'Enter a valid email.' : null,
    phone: !form.phone ? 'Enter a contact number.' : !/^[0-9 +()]{8,}$/.test(form.phone) ? 'Enter a valid phone number.' : null,
    dob: !form.dob ? 'Enter your date of birth.' : null,
    password: !form.password ? 'Create a password.' : form.password.length < 8 ? 'At least 8 characters.' : null,
    confirm: form.confirm !== form.password ? 'Passwords don\'t match.' : null,
  };
  const hasErr = Object.values(errs).some(Boolean) || !form.connection || !form.terms;
  const go = () => { setTouched(true); if (!hasErr) onContinue(); };
  const E = (k) => touched ? errs[k] : null;

  return (
    <div className="flow-card">
      <div className="flow-head"><h2>Tell us about you</h2><p>This sets up your account and your switch.</p></div>
      <div className="card card-outline">
        <div className="grid-2" style={{ gridTemplateColumns: '1fr 1fr', gap: 18 }}>
          <Field label="First name" placeholder="Maya" value={form.first} onChange={set('first')} error={E('first')} />
          <Field label="Last name" placeholder="Brennan" value={form.last} onChange={set('last')} error={E('last')} />
        </div>
        <Field label="Email address" type="email" placeholder="you@example.com" value={form.email} onChange={set('email')} error={E('email')} icon="mail" />
        <div className="grid-2" style={{ gridTemplateColumns: '1fr 1fr', gap: 18 }}>
          <Field label="Phone number" placeholder="0400 000 000" value={form.phone} onChange={set('phone')} error={E('phone')} icon="phone" inputMode="tel" />
          <Field label="Date of birth" type="date" value={form.dob} onChange={set('dob')} error={E('dob')} />
        </div>
        <div className="grid-2" style={{ gridTemplateColumns: '1fr 1fr', gap: 18 }}>
          <Field label="Create password" type="password" placeholder="At least 8 characters" value={form.password} onChange={set('password')} error={E('password')} valid={touched && !errs.password} />
          <Field label="Confirm password" type="password" placeholder="Re-enter password" value={form.confirm} onChange={set('confirm')} error={E('confirm')} valid={touched && form.confirm && !errs.confirm} />
        </div>

        <div className="field-label" style={{ marginTop: 8, marginBottom: 10 }}>What's happening at this property?</div>
        <div style={{ display: 'grid', gap: 10 }}>
          {[
            { id: 'transfer', t: 'I already have power here with another retailer', s: 'We\'ll coordinate a seamless transfer — no interruption to your supply.' },
            { id: 'movein', t: 'I\'m moving in to this property', s: 'Tell us your move-in date on the next step and we\'ll arrange connection.' },
          ].map(o => (
            <label key={o.id} className={'radio-card' + (form.connection === o.id ? ' sel' : '')}>
              <input className="radio" type="radio" name="connection" checked={form.connection === o.id} onChange={() => setForm({ ...form, connection: o.id })} />
              <div><div className="ctext">{o.t}</div><div className="csub">{o.s}</div></div>
            </label>
          ))}
        </div>
        {touched && !form.connection && <div className="field-hint" style={{ color: '#B73E3E', display: 'flex', gap: 5, marginTop: 8 }}><Icon n="alert" size={14} /> Choose your connection type.</div>}

        <div className="consent" style={{ marginTop: 22 }}>
          {[
            { k: 'terms', t: 'I\'ve read and accept the Terms, Energy Price Fact Sheet and Basic Plan Information.', required: true },
            { k: 'authorise', t: 'I authorise Renegade to arrange my transfer and obtain my meter and consumption data.' },
            { k: 'marketing', t: 'Send me product updates and energy-saving tips. (You can opt out anytime.)' },
          ].map(c => (
            <label className="consent-row" key={c.k}>
              <input className="cbox" type="checkbox" checked={!!form[c.k]} onChange={e => setForm({ ...form, [c.k]: e.target.checked })} />
              <div className="ctext">{c.t}{c.required && <span style={{ color: 'var(--accent-press)' }}> *</span>}</div>
            </label>
          ))}
        </div>
        {touched && !form.terms && <div className="field-hint" style={{ color: '#B73E3E', display: 'flex', gap: 5, marginTop: 8 }}><Icon n="alert" size={14} /> You must accept the Terms to continue.</div>}
      </div>
      <div className="flow-nav">
        <Button variant="secondary" size="lg" onClick={onBack}><Icon n="arrowLeft" size={18} /> Back</Button>
        <Button variant="primary" size="lg" onClick={go}>Continue <Icon n="arrowRight" size={18} /></Button>
      </div>
    </div>
  );
};

/* ---------------- Step 4: review ---------------- */
const ReviewStep = ({ property, planId, form, onBack, onConfirm }) => {
  const plan = PLANS[planId] || PLANS.tou;
  const [submitting, setSubmitting] = sUseState(false);
  const submit = () => { setSubmitting(true); setTimeout(onConfirm, 1300); };
  return (
    <div className="flow-card">
      <div className="flow-head"><h2>Review &amp; confirm</h2><p>One last look before we set everything up.</p></div>
      <div className="card card-outline">
        <Row k="Supply address" v={property.address} />
        <Row k="Account holder" v={`${form.first} ${form.last}`} />
        <Row k="Email" v={form.email} />
        <Row k="Connection" v={form.connection === 'movein' ? 'Moving in' : 'Transfer from current retailer'} />
        <hr className="hr" />
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', flexWrap: 'wrap', gap: 12 }}>
          <div>
            <div className="eyebrow">Your plan</div>
            <div style={{ fontSize: 20, fontWeight: 700, marginTop: 6 }}>{plan.name}</div>
            <div style={{ fontSize: 13.5, color: 'var(--fg-2)', marginTop: 2 }}>{plan.refPct}% below reference · 12-month rate guarantee</div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div className="amt tnum" style={{ fontSize: 34, fontWeight: 700, letterSpacing: '-0.03em' }}>{fmt$0(plan.yearly / 12)}<span style={{ fontSize: 14, color: 'var(--fg-3)', fontWeight: 500 }}> /mo est.</span></div>
            <div style={{ fontSize: 12.5, color: 'var(--fg-3)' }} className="tnum">{fmt$0(plan.yearly)}/yr</div>
          </div>
        </div>
      </div>

      <div className="card card-outline" style={{ marginTop: 20 }}>
        <div className="section-label">How you'll pay</div>
        <div style={{ display: 'grid', gap: 10 }}>
          {[
            { id: 'dd', t: 'Direct debit', s: 'Auto-paid on the due date from your bank or card.' },
            { id: 'bpay', t: 'BPAY / manual', s: 'We\'ll send a bill each cycle; you pay when you like.' },
          ].map(o => (
            <label key={o.id} className={'radio-card' + ((form.payment || 'dd') === o.id ? ' sel' : '')}>
              <input className="radio" type="radio" name="payment" checked={(form.payment || 'dd') === o.id} onChange={() => form.setPayment && form.setPayment(o.id)} readOnly />
              <div><div className="ctext">{o.t}</div><div className="csub">{o.s}</div></div>
            </label>
          ))}
        </div>
        <div className="banner banner-info" style={{ marginTop: 16 }}>
          <Icon n="info" size={18} />
          <div>No payment is taken today. Your first bill arrives after your first full billing cycle.</div>
        </div>
      </div>

      <div className="flow-nav">
        <Button variant="secondary" size="lg" onClick={onBack} disabled={submitting}><Icon n="arrowLeft" size={18} /> Back</Button>
        <Button variant="primary" size="lg" onClick={submit} disabled={submitting}>
          {submitting ? <><Spinner on="dark" /> Setting up your account…</> : <>Confirm &amp; switch <Icon n="checkCircle" size={18} /></>}
        </Button>
      </div>
    </div>
  );
};
const Row = ({ k, v }) => (
  <div style={{ display: 'flex', justifyContent: 'space-between', gap: 16, padding: '10px 0', borderBottom: '1px solid var(--bg-sunken)' }}>
    <span style={{ fontSize: 13.5, color: 'var(--fg-2)' }}>{k}</span>
    <span style={{ fontSize: 14, fontWeight: 600, textAlign: 'right' }}>{v}</span>
  </div>
);

/* ---------------- Confirmation ---------------- */
const Confirmation = ({ form, planId, onPortal }) => {
  const plan = PLANS[planId] || PLANS.tou;
  return (
    <div className="flow-card">
      <div className="confirm">
        <div className="cico"><Icon n="checkCircle" size={42} /></div>
        <h2 style={{ fontSize: 34 }}>You're in, {form.first || 'welcome'}.</h2>
        <p style={{ marginTop: 14, fontSize: 17 }}>Welcome to Renegade. We've started your switch to <b>{plan.name}</b> and emailed your welcome pack to {form.email || 'your inbox'}.</p>
        <div className="card card-sunken" style={{ marginTop: 28, textAlign: 'left' }}>
          <div className="section-label">What happens next</div>
          {['We notify your current retailer and coordinate the transfer (3–5 business days).', 'Your supply never switches off — only the name on the bill changes.', 'Your first bill lands after one full billing cycle.'].map((t, i) => (
            <div key={i} style={{ display: 'flex', gap: 12, padding: '10px 0', alignItems: 'flex-start' }}>
              <Icon n="checkCircle" size={18} style={{ color: 'var(--delta-positive)', flex: 'none', marginTop: 1 }} />
              <span style={{ fontSize: 14.5 }}>{t}</span>
            </div>
          ))}
        </div>
        <div style={{ marginTop: 28 }}>
          <Button variant="primary" size="lg" onClick={onPortal}>Go to your account <Icon n="arrowRight" size={18} /></Button>
        </div>
      </div>
    </div>
  );
};

/* ---------------- Flow shell ---------------- */
const SignupFlow = ({ solarGate, initLookup, onExitToPortal }) => {
  const [step, setStep] = sUseState(0);
  const [property, setProperty] = sUseState(null);
  const [selectedPlan, setSelectedPlan] = sUseState('tou');
  const [form, setForm] = sUseState({ first: '', last: '', email: '', phone: '', dob: '', password: '', confirm: '', connection: '', terms: false, authorise: true, marketing: false, payment: 'dd' });

  const goPlan = () => { if (selectedPlan === 'solar' || PLANS[selectedPlan]) setStep(2); };

  return (
    <div className="flow-wrap">
      <div className="container">
        {step < 4 && <Stepper step={step} />}
        {step === 0 && <LookupStep initMode={initLookup && initLookup.mode} initValue={initLookup && initLookup.value}
          onFound={(p) => { setProperty(p); setSelectedPlan(p.solar ? 'solar' : 'tou'); setStep(1); }} />}
        {step === 1 && (property
          ? <PropertyPlanStep property={property} setProperty={(p) => { if (!p) { setStep(0); } else setProperty(p); }}
              solarGate={solarGate} selectedPlan={selectedPlan} setSelectedPlan={setSelectedPlan} onContinue={goPlan} />
          : <LookupStep onFound={(p) => { setProperty(p); setSelectedPlan(p.solar ? 'solar' : 'tou'); }} />)}
        {step === 2 && <DetailsStep form={form} setForm={setForm} onBack={() => setStep(1)} onContinue={() => setStep(3)} />}
        {step === 3 && <ReviewStep property={property} planId={selectedPlan} form={form} onBack={() => setStep(2)} onConfirm={() => setStep(4)} />}
        {step === 4 && <Confirmation form={form} planId={selectedPlan} onPortal={onExitToPortal} />}
      </div>
    </div>
  );
};
window.SignupFlow = SignupFlow;
