// Cost Estimator — guided multi-step inputs → indicative range
// CRITICAL: ranges are illustrative for prototype. The brief mandates "indicative only".

const SETUP_BASE = {
  mainland:  { low: 25000, high: 60000, name: 'Mainland' },
  freezone:  { low: 12000, high: 45000, name: 'Free Zone' },
  offshore:  { low: 12000, high: 22000, name: 'Offshore' }
};

const ZONE_PRESETS = {
  mainland: ['DED Dubai', 'Abu Dhabi DED', 'Sharjah Economic Dept', 'RAK DED'],
  freezone: ['IFZA', 'DMCC', 'Meydan', 'RAKEZ', 'SHAMS', 'SPC', 'DAFZA', 'JAFZA'],
  offshore: ['JAFZA Offshore', 'RAK ICC', 'Ajman Offshore']
};

const ACTIVITIES = ['Trading', 'Consulting / Professional', 'E-commerce', 'Media & Marketing', 'Tech / SaaS', 'Holding company', 'Real estate', 'Other'];

const OFFICES = [
  { id: 'flexi', name: 'Flexi-desk', sub: 'Shared address, visa-eligible', addLow: 0, addHigh: 4000 },
  { id: 'serviced', name: 'Serviced office', sub: 'Private room at our HQ', addLow: 12000, addHigh: 28000 },
  { id: 'physical', name: 'Physical office', sub: 'Standalone leased space', addLow: 35000, addHigh: 120000 }
];

const VISA_COST_PER = 3500; // indicative add-on per visa

const fmt = (n) => 'AED ' + (n / 1000).toFixed(0) + 'k';

const Estimator = ({ lang }) => {
  const [step, setStep] = useState(0);
  const [setup, setSetup] = useState('freezone');
  const [zone, setZone] = useState(null);
  const [visas, setVisas] = useState(2);
  const [office, setOffice] = useState('flexi');
  const [activity, setActivity] = useState('Consulting / Professional');
  const [submitted, setSubmitted] = useState(false);
  const [form, setForm] = useState({ name: '', email: '', phone: '' });

  const STEPS = ['Setup type', 'Jurisdiction', 'Visas & office', 'Activity', 'Your estimate'];

  // compute indicative range
  const computed = useMemo(() => {
    const base = SETUP_BASE[setup];
    const ofc = OFFICES.find(o => o.id === office);
    const visaAdd = (setup === 'offshore' ? 0 : visas * VISA_COST_PER);
    const low = base.low + (ofc.addLow) + visaAdd * 0.85;
    const high = base.high + (ofc.addHigh) + visaAdd * 1.15;
    return { low: Math.round(low / 1000) * 1000, high: Math.round(high / 1000) * 1000 };
  }, [setup, visas, office]);

  const reset = () => { setStep(0); setSetup('freezone'); setZone(null); setVisas(2); setOffice('flexi'); setActivity('Consulting / Professional'); setSubmitted(false); };

  return (
    <section id="estimator" style={{ background: 'var(--paper-2)' }}>
      <div className="container">
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 80, alignItems: 'end', marginBottom: 48 }} className="est-head">
          <div>
            <div className="eyebrow" style={{ marginBottom: 18 }}><span className="dot" />Indicative cost estimator</div>
            <h2 className="h2">How much does it cost to open a business in the UAE?</h2>
          </div>
          <div>
            <p className="lede" style={{ marginBottom: 14 }}>Answer four questions. Get an honest indicative range in seconds — and a precise quote at consultation, where we can factor in your activity, ownership and government fees on the day.</p>
            <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, padding: '7px 12px', borderRadius: 999, background: 'var(--accent-tint)', border: '1px solid var(--accent-soft)', color: 'var(--accent-2)', fontSize: 12.5, fontFamily: 'JetBrains Mono, monospace' }}>
              <Icon name="shield" size={14} /> Government fees change — this is a range, not a quote.
            </div>
          </div>
        </div>

        <div style={{
          background: 'var(--surface)', borderRadius: 20, border: '1px solid var(--line)',
          overflow: 'hidden', boxShadow: '0 24px 60px -30px rgba(11,31,51,0.18)'
        }}>
          {/* Progress */}
          <div style={{ display: 'flex', borderBottom: '1px solid var(--line)' }}>
            {STEPS.map((s, i) => (
              <button key={s} onClick={() => i < step && setStep(i)} disabled={i > step}
                style={{
                  flex: 1, padding: '20px 18px', background: 'transparent',
                  border: 'none', borderInlineEnd: i < STEPS.length - 1 ? '1px solid var(--line)' : 'none',
                  textAlign: 'start', cursor: i <= step ? 'pointer' : 'default',
                  opacity: i <= step ? 1 : 0.5
                }}>
                <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 11, letterSpacing: '0.1em', color: 'var(--muted)', marginBottom: 5 }}>
                  STEP 0{i + 1}
                </div>
                <div style={{ fontFamily: 'Sora, sans-serif', fontWeight: 500, fontSize: 14.5, color: step === i ? 'var(--accent-2)' : 'var(--ink)', display: 'flex', alignItems: 'center', gap: 8 }}>
                  {step > i && <Icon name="check" size={14} color="var(--success)" />}
                  {s}
                </div>
              </button>
            ))}
          </div>

          {/* Body */}
          <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', minHeight: 460 }} className="est-body">
            {/* Left: inputs */}
            <div style={{ padding: 40, borderInlineEnd: '1px solid var(--line)' }}>
              {step === 0 && (
                <Step title="What type of company do you want to set up?" sub="The biggest cost driver. We'll show indicative bands for each.">
                  <div style={{ display: 'grid', gap: 12 }}>
                    {Object.entries(SETUP_BASE).map(([key, v]) => (
                      <OptionCard key={key} active={setup === key} onClick={() => setSetup(key)}
                        title={v.name}
                        meta={`From ${fmt(v.low)}`}
                        desc={key === 'mainland' ? 'Trade anywhere in the UAE, including the local market.' : key === 'freezone' ? '100% foreign ownership, tax-friendly, 15+ specialised zones.' : 'International holding & asset structure. No UAE visas.'}
                      />
                    ))}
                  </div>
                </Step>
              )}
              {step === 1 && (
                <Step title={`Which ${SETUP_BASE[setup].name.toLowerCase()} option?`} sub="Pick the closest match — we'll refine at consultation.">
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10 }}>
                    {ZONE_PRESETS[setup].map(z => (
                      <button key={z} onClick={() => setZone(z)} style={{
                        padding: '12px 18px', borderRadius: 10,
                        background: zone === z ? 'var(--ink)' : 'var(--paper)',
                        border: '1px solid ' + (zone === z ? 'var(--ink)' : 'var(--line)'),
                        color: zone === z ? 'var(--paper)' : 'var(--ink)',
                        fontFamily: 'DM Sans', fontSize: 14, fontWeight: 500, cursor: 'pointer'
                      }}>{z}</button>
                    ))}
                  </div>
                  <button onClick={() => setZone(zone || 'Not sure — recommend one')} style={{
                    marginTop: 18, background: 'transparent', border: 'none',
                    color: 'var(--accent-2)', fontWeight: 500, cursor: 'pointer', padding: 0
                  }}>I'm not sure — recommend the best one →</button>
                </Step>
              )}
              {step === 2 && (
                <Step title="Visas and office" sub="Each UAE residence visa adds roughly AED 3.5k indicative. Office tier sets your visa quota.">
                  <div style={{ marginBottom: 30 }}>
                    <div className="eyebrow" style={{ marginBottom: 12 }}>UAE residence visas needed</div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
                      <button onClick={() => setVisas(Math.max(0, visas - 1))} style={iconBtn} disabled={setup === 'offshore'}><Icon name="minus" size={16} /></button>
                      <div className="num" style={{ fontSize: 36, fontFamily: 'Sora, sans-serif', fontWeight: 600, minWidth: 50, textAlign: 'center', color: setup === 'offshore' ? 'var(--muted-2)' : 'var(--ink)' }}>
                        {setup === 'offshore' ? '—' : visas}
                      </div>
                      <button onClick={() => setVisas(Math.min(12, visas + 1))} style={iconBtn} disabled={setup === 'offshore'}><Icon name="plus" size={16} /></button>
                      {setup === 'offshore' && <span style={{ fontSize: 13, color: 'var(--muted)', marginInlineStart: 12 }}>Offshore doesn't issue UAE visas.</span>}
                    </div>
                  </div>

                  <div className="eyebrow" style={{ marginBottom: 12 }}>Office requirement</div>
                  <div style={{ display: 'grid', gap: 10 }}>
                    {OFFICES.map(o => (
                      <OptionCard key={o.id} compact active={office === o.id} onClick={() => setOffice(o.id)}
                        title={o.name} meta={`+${fmt(o.addLow)}–${fmt(o.addHigh)}`} desc={o.sub} />
                    ))}
                  </div>
                </Step>
              )}
              {step === 3 && (
                <Step title="What activity will the company do?" sub="Just to colour the recommendation — we won't overload you with classes here.">
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10 }}>
                    {ACTIVITIES.map(a => (
                      <button key={a} onClick={() => setActivity(a)} style={{
                        padding: '12px 18px', borderRadius: 10,
                        background: activity === a ? 'var(--ink)' : 'var(--paper)',
                        border: '1px solid ' + (activity === a ? 'var(--ink)' : 'var(--line)'),
                        color: activity === a ? 'var(--paper)' : 'var(--ink)',
                        fontFamily: 'DM Sans', fontSize: 14, fontWeight: 500, cursor: 'pointer'
                      }}>{a}</button>
                    ))}
                  </div>
                </Step>
              )}
              {step === 4 && !submitted && (
                <Step title="Your estimate is ready." sub="Leave your details to get the full breakdown and book a free consultation.">
                  <form onSubmit={(e) => { e.preventDefault(); setSubmitted(true); }} style={{ display: 'grid', gap: 14, maxWidth: 480 }}>
                    <Field label="Full name" value={form.name} onChange={v => setForm({ ...form, name: v })} />
                    <Field label="Work email" type="email" value={form.email} onChange={v => setForm({ ...form, email: v })} />
                    <Field label="Phone / WhatsApp" type="tel" value={form.phone} onChange={v => setForm({ ...form, phone: v })} />
                    <button type="submit" className="btn btn-primary" style={{ marginTop: 8, justifyContent: 'flex-start' }}>
                      Send my estimate & book consultation <Icon name="arrow" size={16} className="arrow" />
                    </button>
                    <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 4 }}>
                      We'll never share your details. Reply within 1 working day.
                    </div>
                  </form>
                </Step>
              )}
              {step === 4 && submitted && (
                <Step title="Sent. We'll be in touch within 1 working day." sub="Want to start the conversation now? Ping us on WhatsApp.">
                  <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
                    <a href="#" className="btn btn-accent">
                      <Icon name="whatsapp" size={18} /> Continue on WhatsApp
                    </a>
                    <button className="btn btn-ghost" onClick={reset}>Start a new estimate</button>
                  </div>
                </Step>
              )}

              {/* nav */}
              {!submitted && (
                <div style={{ marginTop: 32, display: 'flex', gap: 12, alignItems: 'center' }}>
                  {step > 0 && <button onClick={() => setStep(step - 1)} className="btn btn-ghost btn-sm">← Back</button>}
                  {step < STEPS.length - 1 && (
                    <button onClick={() => setStep(step + 1)} className="btn btn-primary btn-sm" style={{ marginInlineStart: 'auto' }}>
                      {step === 3 ? 'See my estimate' : 'Continue'} <Icon name="arrow" size={14} />
                    </button>
                  )}
                </div>
              )}
            </div>

            {/* Right: live summary */}
            <div style={{ background: 'var(--paper)', padding: 36, display: 'flex', flexDirection: 'column' }}>
              <div className="eyebrow" style={{ marginBottom: 18 }}>Your indicative estimate</div>

              <div style={{ marginBottom: 28 }}>
                <div className="num" style={{
                  fontFamily: 'Sora, sans-serif', fontWeight: 600, fontSize: 44,
                  letterSpacing: '-0.02em', color: 'var(--ink)', lineHeight: 1
                }}>
                  {fmt(computed.low)}<span style={{ color: 'var(--muted-2)' }}> – </span>{fmt(computed.high)}
                </div>
                <div style={{ marginTop: 8, fontSize: 13, color: 'var(--muted)' }}>
                  All-in, first-year indicative range
                </div>
              </div>

              <div style={{ display: 'flex', flexDirection: 'column', gap: 14, paddingTop: 4, borderTop: '1px solid var(--line)' }}>
                <SumRow label="Setup type" value={SETUP_BASE[setup].name} />
                <SumRow label="Jurisdiction" value={zone || '—'} />
                <SumRow label="Visas" value={setup === 'offshore' ? '—' : `${visas}`} />
                <SumRow label="Office" value={OFFICES.find(o => o.id === office).name} />
                <SumRow label="Activity" value={activity} />
              </div>

              <div style={{
                marginTop: 'auto', paddingTop: 28, fontSize: 12.5, color: 'var(--muted)',
                lineHeight: 1.5, borderTop: '1px dashed var(--line)'
              }}>
                <strong style={{ color: 'var(--ink)' }}>Indicative only.</strong> UAE government fees are
                set by the relevant authority and change. Your exact quote — including activity-specific
                approvals, share capital and PRO costs — comes from a free consultation.
              </div>
            </div>
          </div>
        </div>
      </div>
      <style>{`
        @media (max-width: 900px) {
          .est-head { grid-template-columns: 1fr !important; gap: 24px !important; }
          .est-body { grid-template-columns: 1fr !important; }
          .est-body > div { border-inline-end: none !important; }
        }
      `}</style>
    </section>
  );
};

const Step = ({ title, sub, children }) => (
  <div key={title} style={{ animation: 'fadeUp .3s cubic-bezier(.2,.7,.2,1) both' }}>
    <h3 className="h3" style={{ fontSize: 24, marginBottom: 6 }}>{title}</h3>
    <p style={{ color: 'var(--muted)', marginTop: 0, marginBottom: 24, fontSize: 15 }}>{sub}</p>
    {children}
  </div>
);

const OptionCard = ({ active, onClick, title, meta, desc, compact }) => (
  <button onClick={onClick} style={{
    textAlign: 'start',
    background: active ? 'var(--ink)' : 'var(--paper)',
    border: '1px solid ' + (active ? 'var(--ink)' : 'var(--line)'),
    borderRadius: 12,
    padding: compact ? '14px 18px' : '18px 22px',
    cursor: 'pointer',
    color: active ? 'var(--paper)' : 'var(--ink)',
    transition: 'all .15s ease',
    display: 'flex', alignItems: 'center', gap: 14
  }}>
    <div style={{
      width: 18, height: 18, borderRadius: 50, flexShrink: 0,
      border: '1.5px solid ' + (active ? 'var(--accent)' : 'var(--line)'),
      background: active ? 'var(--accent)' : 'transparent',
      display: 'flex', alignItems: 'center', justifyContent: 'center'
    }}>{active && <Icon name="check" size={11} color="var(--ink)" stroke={2.5} />}</div>
    <div style={{ flex: 1 }}>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 12, marginBottom: compact ? 0 : 4 }}>
        <span style={{ fontFamily: 'Sora, sans-serif', fontWeight: 500, fontSize: compact ? 15 : 17 }}>{title}</span>
        <span className="num" style={{ fontSize: 12.5, color: active ? 'rgba(243,238,229,0.7)' : 'var(--muted)', fontFamily: 'JetBrains Mono, monospace' }}>{meta}</span>
      </div>
      {desc && !compact && <div style={{ fontSize: 13.5, color: active ? 'rgba(243,238,229,0.7)' : 'var(--muted)' }}>{desc}</div>}
      {desc && compact && <div style={{ fontSize: 12.5, color: active ? 'rgba(243,238,229,0.7)' : 'var(--muted)', marginTop: 2 }}>{desc}</div>}
    </div>
  </button>
);

const Field = ({ label, type = 'text', value, onChange }) => (
  <label style={{ display: 'block' }}>
    <span style={{ display: 'block', fontSize: 13, color: 'var(--muted)', marginBottom: 6, fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.05em' }}>{label}</span>
    <input type={type} value={value} onChange={e => onChange(e.target.value)} required
      style={{
        width: '100%', padding: '12px 14px',
        background: 'var(--paper)', border: '1px solid var(--line)', borderRadius: 8,
        fontFamily: 'DM Sans', fontSize: 15, color: 'var(--ink)', outline: 'none'
      }}
      onFocus={e => e.target.style.borderColor = 'var(--accent)'}
      onBlur={e => e.target.style.borderColor = 'var(--line)'}
    />
  </label>
);

const SumRow = ({ label, value }) => (
  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 12, fontSize: 14 }}>
    <span style={{ color: 'var(--muted)', fontFamily: 'JetBrains Mono, monospace', fontSize: 11.5, letterSpacing: '0.06em', textTransform: 'uppercase' }}>{label}</span>
    <span style={{ color: 'var(--ink)', fontWeight: 500, textAlign: 'end' }}>{value}</span>
  </div>
);

const iconBtn = {
  width: 40, height: 40, borderRadius: 50,
  background: 'var(--paper)', border: '1px solid var(--line)',
  display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
  cursor: 'pointer', color: 'var(--ink)'
};

Object.assign(window, { Estimator });
