/* ===== screen-calculator.jsx ===== */

// Indicative cost coefficients — clearly typed, NOT a fixed price list.
// All values are illustrative ranges (AED) for design demonstration only.
const CALC_RANGES = (() => {
  // jurisdiction base ranges
  const J = {
    "dubai-mainland": [18000, 32000],
    "dmcc":           [22000, 38000],
    "difc":           [48000, 92000],
    "jafza":          [28000, 46000],
    "meydan":         [12500, 22000],
    "dubai-south":    [18000, 30000],
    "ifza-d3":        [14000, 26000],
    "adgm":           [44000, 86000],
    "rakez":          [10500, 19000],
    "rak-icc":        [9500, 16000],
    "bvi":            [14000, 24000],
    "ksa":            [42000, 78000],
    "qatar":          [38000, 72000],
  };
  // activity multiplier
  const A = {
    "trading":     1.0,
    "consulting":  0.92,
    "ecommerce":   0.98,
    "tech":        1.05,
    "fnb":         1.18,
    "financial":   1.55,
  };
  // office multiplier
  const O = {
    "flexi":    1.0,
    "shared":   1.18,
    "private":  1.55,
    "warehouse":2.1,
  };
  // visa cost (per visa)
  const visa = [4800, 7600];

  function estimate({ zone, activity, visas, office, shareholders }) {
    const base = J[zone] || [15000, 28000];
    const am = A[activity] || 1;
    const om = O[office] || 1;
    const lo = Math.round((base[0] * am * om + visa[0] * visas) / 100) * 100;
    const hi = Math.round((base[1] * am * om + visa[1] * visas) / 100) * 100;
    return { low: lo, high: hi };
  }
  return { estimate, J, A, O };
})();
window.CALC_RANGES = CALC_RANGES;

function CalculatorScreen({ locale, setRoute }) {
  const s = STR[locale];
  const [step, setStep] = React.useState(0);
  const [form, setForm] = React.useState({
    zone: "dmcc",
    activity: "trading",
    visas: 2,
    shareholders: 1,
    office: "flexi",
    name: "", email: "", phone: "",
  });
  const update = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const r = CALC_RANGES.estimate(form);
  const steps = ["Jurisdiction", "Activity", "Visas & team", "Office", "See estimate", "Talk to an advisor"];

  return (
    <main>
      <section style={{ padding: "56px 0 36px", background: "var(--paper-2)", borderBottom: "1px solid var(--line)" }}>
        <div className="wrap-tight">
          <div className="eyebrow" style={{ marginBottom: 12 }}>Cost calculator</div>
          <h1 style={{ marginBottom: 16, fontSize: "clamp(36px,3.6vw,56px)" }}>
            Indicative setup cost, in <span style={{ color: "var(--accent-deep)", fontFamily: "Fraunces, serif", fontStyle: "italic", fontWeight: 500 }}>about two minutes.</span>
          </h1>
          <p className="muted" style={{ fontSize: 17, maxWidth: 680 }}>
            We show a range — never a fixed number. Government fees move, packages bundle, and your specific activity matters. An advisor confirms the exact figure on a free call.
          </p>
        </div>
      </section>

      <section className="section" style={{ paddingTop: 56 }}>
        <div className="wrap-tight" style={{ display: "grid", gridTemplateColumns: "260px 1fr", gap: 56 }}>
          {/* stepper */}
          <aside>
            <div style={{ position: "sticky", top: 96 }}>
              {steps.map((label, i) => (
                <button key={label} onClick={() => setStep(i)} style={{
                  display: "flex", alignItems: "center", gap: 14, padding: "12px 0",
                  background: "transparent", border: 0, width: "100%", textAlign: "left",
                  color: i === step ? "var(--cz-ink)" : "var(--muted)",
                  fontWeight: i === step ? 600 : 500, fontSize: 14,
                  cursor: "pointer",
                }}>
                  <span style={{
                    width: 28, height: 28, borderRadius: 8,
                    background: i < step ? "var(--accent)" : i === step ? "var(--cz-ink)" : "var(--paper-3)",
                    color: i <= step ? "#fff" : "var(--muted)",
                    display: "flex", alignItems: "center", justifyContent: "center",
                    fontFamily: "var(--f-mono)", fontSize: 12, fontWeight: 600,
                  }}>{i < step ? <Icon name="check" size={14}/> : String(i + 1).padStart(2, "0")}</span>
                  {label}
                </button>
              ))}
              <div style={{ marginTop: 32, padding: 16, borderRadius: 12, background: "var(--accent-tint)", border: "1px solid color-mix(in srgb, var(--accent) 24%, transparent)" }}>
                <div style={{ fontSize: 12, color: "var(--accent-deep)", fontWeight: 600, marginBottom: 6, textTransform: "uppercase", letterSpacing: ".1em" }}>Need a human?</div>
                <p style={{ fontSize: 13, color: "var(--cz-ink)", marginBottom: 10 }}>Skip the form and chat to an advisor right now.</p>
                <a href={waLink()} className="btn btn-sm btn-accent" style={{ width: "100%", justifyContent: "center" }}>
                  <Icon name="wa" size={14}/> WhatsApp now
                </a>
              </div>
            </div>
          </aside>

          {/* form panel */}
          <div className="card" style={{ padding: 0, overflow: "hidden", background: "#fff" }}>
            <div style={{ padding: "10px 28px", borderBottom: "1px solid var(--line)", background: "var(--paper-2)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <div style={{ display: "flex", gap: 4 }}>
                {steps.map((_, i) => (
                  <div key={i} style={{ width: 28, height: 4, borderRadius: 2,
                    background: i <= step ? "var(--accent)" : "var(--line-strong)" }}/>
                ))}
              </div>
              <span className="chip"><span className="chip-dot"></span>Indicative</span>
            </div>

            <div style={{ padding: 36, minHeight: 460 }}>
              {step === 0 && <StepJurisdiction form={form} update={update}/>}
              {step === 1 && <StepActivity form={form} update={update}/>}
              {step === 2 && <StepVisas form={form} update={update}/>}
              {step === 3 && <StepOffice form={form} update={update}/>}
              {step === 4 && <StepEstimate form={form} r={r}/>}
              {step === 5 && <StepLead form={form} update={update} r={r}/>}
            </div>

            <div style={{ padding: 24, borderTop: "1px solid var(--line)", display: "flex", justifyContent: "space-between", alignItems: "center", background: "var(--paper-2)" }}>
              <div style={{ fontSize: 12, color: "var(--muted)" }}>{STR[locale].indicative}</div>
              <div style={{ display: "flex", gap: 12 }}>
                {step > 0 && <button className="btn btn-sm btn-ghost" onClick={() => setStep(step - 1)}>Back</button>}
                {step < 5 && <button className="btn btn-sm btn-accent" onClick={() => setStep(step + 1)}>
                  {step === 4 ? "Get my estimate" : "Continue"} <Icon name="arrow" size={14}/>
                </button>}
                {step === 5 && form.email && (
                  <button className="btn btn-sm btn-primary" onClick={() => alert("Demo only — your advisor would be in touch within 30 minutes.")}>
                    Send to my advisor <Icon name="arrow" size={14}/>
                  </button>
                )}
              </div>
            </div>
          </div>
        </div>
      </section>
    </main>
  );
}

function FieldGrid({ children, cols = 2 }) {
  return <div style={{ display: "grid", gridTemplateColumns: `repeat(${cols}, 1fr)`, gap: 12 }}>{children}</div>;
}

function CardOption({ active, onClick, title, sub, icon }) {
  return (
    <button onClick={onClick} style={{
      padding: 18, borderRadius: 12, textAlign: "left",
      border: "1.5px solid " + (active ? "var(--accent)" : "var(--line-strong)"),
      background: active ? "var(--accent-tint)" : "#fff",
      cursor: "pointer", display: "flex", flexDirection: "column", gap: 8,
      transition: "border-color .15s ease, background .15s ease",
    }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
        <div style={{
          width: 36, height: 36, borderRadius: 8, background: active ? "var(--accent)" : "var(--paper-2)",
          color: active ? "#fff" : "var(--cz-ink)",
          display: "flex", alignItems: "center", justifyContent: "center", fontWeight: 600,
        }}>{icon}</div>
        {active && <div style={{ width: 18, height: 18, borderRadius: "50%", background: "var(--accent)", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="check" size={12}/></div>}
      </div>
      <div style={{ fontWeight: 600, fontSize: 15 }}>{title}</div>
      <div style={{ fontSize: 12.5, color: "var(--muted)" }}>{sub}</div>
    </button>
  );
}

function StepJurisdiction({ form, update }) {
  const groups = [
    { label: "Free zones (most flexible)", items: ["dmcc", "meydan", "ifza-d3", "dubai-south", "jafza", "difc", "adgm", "rakez"] },
    { label: "Mainland", items: ["dubai-mainland"] },
    { label: "Offshore & international", items: ["rak-icc", "bvi"] },
    { label: "Regional", items: ["ksa", "qatar"] },
  ];
  return (
    <div>
      <h3 style={{ fontSize: 22, marginBottom: 6 }}>Where do you want to set up?</h3>
      <p className="muted" style={{ marginBottom: 24, fontSize: 14 }}>Pick the jurisdiction — we'll adjust the rest of the form to its rules.</p>
      {groups.map(g => (
        <div key={g.label} style={{ marginBottom: 22 }}>
          <div className="eyebrow" style={{ marginBottom: 10 }}>{g.label}</div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 10 }}>
            {g.items.map(id => {
              const j = DATA.jurisdictions.find(x => x.id === id);
              if (!j) return null;
              const active = form.zone === id;
              return (
                <button key={id} onClick={() => update("zone", id)} style={{
                  padding: "12px 14px", borderRadius: 10, textAlign: "left",
                  border: "1.5px solid " + (active ? "var(--accent)" : "var(--line-strong)"),
                  background: active ? "var(--accent-tint)" : "#fff",
                  cursor: "pointer", display: "flex", flexDirection: "column", gap: 2,
                }}>
                  <div style={{ fontWeight: 600, fontSize: 14, color: "var(--cz-ink)" }}>{j.name}</div>
                  <div style={{ fontSize: 12, color: "var(--muted)" }}>{j.suited}</div>
                </button>
              );
            })}
          </div>
        </div>
      ))}
    </div>
  );
}

function StepActivity({ form, update }) {
  const items = [
    { id: "trading",    title: "Trading / general",        sub: "Buy & sell goods, retail, wholesale",  icon: "T" },
    { id: "consulting", title: "Consulting & services",    sub: "Advisory, agency, professional services", icon: "C" },
    { id: "ecommerce",  title: "E-commerce",               sub: "Online retail, fulfilment, dropship",  icon: "e" },
    { id: "tech",       title: "Tech & software",          sub: "SaaS, platforms, IT consulting",       icon: "{}" },
    { id: "fnb",        title: "F&B / cloud kitchen",      sub: "Restaurants, cloud kitchens, catering", icon: "♨" },
    { id: "financial",  title: "Financial services",       sub: "Asset mgmt, fintech, brokerage (DIFC/ADGM)", icon: "$" },
  ];
  return (
    <div>
      <h3 style={{ fontSize: 22, marginBottom: 6 }}>What will the company do?</h3>
      <p className="muted" style={{ marginBottom: 24, fontSize: 14 }}>Activity selection shapes which licence and approvals we'll need.</p>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 12 }}>
        {items.map(it => (
          <CardOption key={it.id} active={form.activity === it.id} onClick={() => update("activity", it.id)}
            title={it.title} sub={it.sub} icon={it.icon}/>
        ))}
      </div>
    </div>
  );
}

function StepVisas({ form, update }) {
  return (
    <div>
      <h3 style={{ fontSize: 22, marginBottom: 6 }}>How many people on visas?</h3>
      <p className="muted" style={{ marginBottom: 32, fontSize: 14 }}>This drives visa quotas, office-size requirements and PRO scope.</p>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 28 }}>
        <div className="card" style={{ padding: 24 }}>
          <div className="eyebrow" style={{ marginBottom: 8 }}>Total visas</div>
          <div style={{ fontFamily: "var(--f-display)", fontSize: 48, fontWeight: 600, color: "var(--cz-ink)", lineHeight: 1 }}>{form.visas}</div>
          <div className="muted" style={{ fontSize: 13, marginBottom: 18 }}>Partners, employees, family</div>
          <input type="range" min={0} max={15} value={form.visas} onChange={e => update("visas", +e.target.value)} style={{ width: "100%", accentColor: "var(--accent)" }}/>
          <div style={{ display: "flex", justifyContent: "space-between", fontSize: 11, color: "var(--muted-2)", marginTop: 6 }}>
            <span>0</span><span>15+</span>
          </div>
        </div>
        <div className="card" style={{ padding: 24 }}>
          <div className="eyebrow" style={{ marginBottom: 8 }}>Shareholders</div>
          <div style={{ fontFamily: "var(--f-display)", fontSize: 48, fontWeight: 600, color: "var(--cz-ink)", lineHeight: 1 }}>{form.shareholders}</div>
          <div className="muted" style={{ fontSize: 13, marginBottom: 18 }}>Individuals + corporate</div>
          <input type="range" min={1} max={7} value={form.shareholders} onChange={e => update("shareholders", +e.target.value)} style={{ width: "100%", accentColor: "var(--accent)" }}/>
          <div style={{ display: "flex", justifyContent: "space-between", fontSize: 11, color: "var(--muted-2)", marginTop: 6 }}>
            <span>1</span><span>7+</span>
          </div>
        </div>
      </div>
      <div style={{ padding: 18, borderRadius: 12, background: "var(--paper-2)", marginTop: 22, fontSize: 13, color: "var(--muted)", display: "flex", gap: 10 }}>
        <span style={{ color: "var(--accent-deep)" }}><Icon name="check" size={16}/></span>
        Visa quotas vary by jurisdiction. The estimate widens the range to keep the figure honest until an advisor confirms.
      </div>
    </div>
  );
}

function StepOffice({ form, update }) {
  const items = [
    { id: "flexi",     title: "Flexi-desk",   sub: "Co-working — most cost-efficient",      icon: "▤" },
    { id: "shared",    title: "Shared office", sub: "Shared address, dedicated desks",      icon: "◫" },
    { id: "private",   title: "Private office", sub: "Your own locked office",              icon: "■" },
    { id: "warehouse", title: "Warehouse / industrial", sub: "Storage + commercial space",  icon: "▥" },
  ];
  return (
    <div>
      <h3 style={{ fontSize: 22, marginBottom: 6 }}>Where will you operate from?</h3>
      <p className="muted" style={{ marginBottom: 24, fontSize: 14 }}>Office type ties to your visa quota and licence package.</p>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 12 }}>
        {items.map(it => (
          <CardOption key={it.id} active={form.office === it.id} onClick={() => update("office", it.id)}
            title={it.title} sub={it.sub} icon={it.icon}/>
        ))}
      </div>
    </div>
  );
}

function StepEstimate({ form, r }) {
  const j = DATA.jurisdictions.find(x => x.id === form.zone);
  return (
    <div>
      <div className="eyebrow" style={{ marginBottom: 12 }}>Your indicative estimate</div>
      <div style={{
        padding: 32, borderRadius: 16,
        background: "linear-gradient(135deg, var(--cz-ink), #0E2E60)",
        color: "#fff", marginBottom: 24,
      }}>
        <div style={{ fontSize: 13, color: "rgba(255,255,255,.65)", textTransform: "uppercase", letterSpacing: ".1em", marginBottom: 8 }}>Setup year one (indicative)</div>
        <div style={{ fontFamily: "var(--f-display)", fontSize: 56, fontWeight: 600, letterSpacing: "-0.02em", lineHeight: 1 }}>
          AED {r.low.toLocaleString()}<span style={{ color: "var(--accent)" }}> — </span>{r.high.toLocaleString()}
        </div>
        <div style={{ marginTop: 18, paddingTop: 18, borderTop: "1px solid rgba(255,255,255,.1)", display: "flex", justifyContent: "space-between", gap: 24, color: "rgba(255,255,255,.85)", fontSize: 13 }}>
          <div><div style={{ color: "rgba(255,255,255,.55)", marginBottom: 4 }}>Jurisdiction</div><b>{j ? j.name : ""}</b></div>
          <div><div style={{ color: "rgba(255,255,255,.55)", marginBottom: 4 }}>Activity</div><b style={{ textTransform: "capitalize" }}>{form.activity}</b></div>
          <div><div style={{ color: "rgba(255,255,255,.55)", marginBottom: 4 }}>Visas</div><b>{form.visas}</b></div>
          <div><div style={{ color: "rgba(255,255,255,.55)", marginBottom: 4 }}>Office</div><b style={{ textTransform: "capitalize" }}>{form.office}</b></div>
        </div>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 12 }}>
        {[
          { l: "Licence & registration", v: "Government fee + zone licence" },
          { l: "Visa & immigration",     v: form.visas + " × employee / partner" },
          { l: "Workspace year one",     v: form.office === "flexi" ? "Flexi-desk package" : form.office === "shared" ? "Shared office" : form.office === "private" ? "Private office" : "Warehouse" },
        ].map(b => (
          <div key={b.l} className="card" style={{ padding: 16 }}>
            <div className="eyebrow" style={{ marginBottom: 6 }}>{b.l}</div>
            <div style={{ fontSize: 14, color: "var(--cz-ink)", fontWeight: 500 }}>{b.v}</div>
          </div>
        ))}
      </div>
      <div style={{ marginTop: 22, padding: 16, borderRadius: 12, background: "var(--accent-tint)", border: "1px solid color-mix(in srgb, var(--accent) 22%, transparent)", display: "flex", gap: 14, fontSize: 13.5 }}>
        <span style={{ color: "var(--accent-deep)", flexShrink: 0 }}><Icon name="check" size={18}/></span>
        <div>
          <b>This is an indicative range, not a quote.</b> Government fees change without notice; activity-specific approvals can add or reduce cost. Your advisor will confirm the exact figure and lock it on a proposal.
        </div>
      </div>
    </div>
  );
}

function StepLead({ form, update, r }) {
  const [submitted, setSubmitted] = React.useState(false);
  if (submitted) {
    return (
      <div style={{ textAlign: "center", padding: "40px 0" }}>
        <div style={{ width: 64, height: 64, borderRadius: "50%", background: "var(--accent)", color: "#fff",
          display: "inline-flex", alignItems: "center", justifyContent: "center", marginBottom: 18 }}>
          <Icon name="check" size={28}/>
        </div>
        <h3 style={{ fontSize: 24, marginBottom: 10 }}>Thanks {form.name.split(" ")[0] || "there"} — your estimate is on its way.</h3>
        <p className="muted" style={{ maxWidth: 460, margin: "0 auto" }}>
          An advisor will reach out within 30 minutes during UAE business hours (Mon–Fri 09:00–18:00, GMT+4). Want to chat now?
        </p>
        <div style={{ display: "flex", gap: 10, justifyContent: "center", marginTop: 22 }}>
          <a className="btn btn-accent" href={waLink(`I just got an estimate of AED ${r.low.toLocaleString()}–${r.high.toLocaleString()}`)}>
            <Icon name="wa" size={14}/> WhatsApp now
          </a>
          <a className="btn btn-ghost" href="tel:+97145677333"><Icon name="phone" size={14}/> Call advisor</a>
        </div>
      </div>
    );
  }
  return (
    <div>
      <h3 style={{ fontSize: 22, marginBottom: 6 }}>Where should we send your estimate?</h3>
      <p className="muted" style={{ marginBottom: 24, fontSize: 14 }}>We'll email you a PDF and put you on a free 30-minute call with an advisor.</p>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginBottom: 14 }}>
        <div className="field"><label>Full name</label><input value={form.name} onChange={e => update("name", e.target.value)} placeholder="Jane Carter"/></div>
        <div className="field"><label>Email</label><input type="email" value={form.email} onChange={e => update("email", e.target.value)} placeholder="jane@company.com"/></div>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginBottom: 14 }}>
        <div className="field"><label>WhatsApp / phone</label><input value={form.phone} onChange={e => update("phone", e.target.value)} placeholder="+971 …"/></div>
        <div className="field"><label>When suits?</label>
          <select defaultValue="anytime">
            <option value="anytime">Anytime in the next 24 hours</option>
            <option>This morning</option><option>This afternoon</option>
            <option>Tomorrow morning</option><option>Tomorrow afternoon</option>
          </select>
        </div>
      </div>
      <div className="field" style={{ marginBottom: 18 }}>
        <label>Anything specific?</label>
        <textarea rows={3} placeholder="E.g. I'm based in London and want to relocate Q3..."/>
      </div>
      <label style={{ display: "flex", gap: 10, fontSize: 13, color: "var(--muted)", marginBottom: 18, alignItems: "flex-start" }}>
        <input type="checkbox" defaultChecked style={{ marginTop: 4, accentColor: "var(--accent)" }}/>
        I agree to be contacted about my UAE business setup. We don't sell data — see Privacy.
      </label>
      <button className="btn btn-accent" style={{ width: "100%", justifyContent: "center" }} onClick={() => form.email && form.name && setSubmitted(true)}>
        Send to my advisor <Icon name="arrow" size={16}/>
      </button>
    </div>
  );
}

Object.assign(window, { CalculatorScreen });
