// MyAirSpace — Guided purchase wizard. Interactive multi-step flow.
const { Button, Card, Field, Select, Checkbox, Callout, Stepper, Badge, Seal } = window.MyAirSpace || {};
const Icon = window.MyAirSpaceIcon;

const STEPS = ["Your details", "Property", "Declaration", "Payment"];

function WizardShell({ children, step }) {
  return (
    <div style={{ minHeight: "100vh", background: "var(--surface-page)", display: "flex", flexDirection: "column" }}>
      <header style={{ borderBottom: "1px solid var(--border-subtle)", background: "var(--surface-card)" }}>
        <div style={{ maxWidth: 720, margin: "0 auto", padding: "16px 28px", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
          <img src="../../assets/logo-wordmark.svg" alt="MyAirSpace" style={{ height: 28 }} />
          <div style={{ display: "flex", alignItems: "center", gap: 8, fontFamily: "var(--font-ui)", fontSize: 13, color: "var(--text-muted)" }}>
            <Icon name="lock" size={14} color="var(--text-muted)" />Secure checkout
          </div>
        </div>
      </header>
      <div style={{ maxWidth: 720, margin: "0 auto", padding: "32px 28px 8px", width: "100%", boxSizing: "border-box" }}>
        <Stepper current={step} steps={STEPS} />
      </div>
      <div style={{ flex: 1, maxWidth: 720, margin: "0 auto", padding: "28px 28px 56px", width: "100%", boxSizing: "border-box" }}>{children}</div>
    </div>
  );
}

function StepHeading({ kicker, title, sub }) {
  return (
    <div style={{ marginBottom: 26 }}>
      <div className="eyebrow" style={{ marginBottom: 8 }}>{kicker}</div>
      <h1 style={{ fontSize: 32, letterSpacing: "-0.02em", marginBottom: sub ? 8 : 0 }}>{title}</h1>
      {sub && <p style={{ fontSize: 16, color: "var(--text-secondary)", lineHeight: 1.55 }}>{sub}</p>}
    </div>
  );
}

function Footer({ onBack, onNext, nextLabel = "Continue", canBack = true }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", marginTop: 32 }}>
      {canBack ? <Button variant="ghost" onClick={onBack} iconLeft={<Icon name="arrow-left" size={16} color="var(--accent-hover)" />}>Back</Button> : <span />}
      <Button variant="primary" onClick={onNext} iconRight={<Icon name="arrow-right" size={16} color="#fff" />}>{nextLabel}</Button>
    </div>
  );
}

function PurchaseWizard() {
  const [step, setStep] = React.useState(0);
  const [data, setData] = React.useState({
    name: "", email: "", line1: "", town: "", postcode: "", propType: "House", declare: false, terms: false,
  });
  const set = (k) => (e) => setData((d) => ({ ...d, [k]: e.target.value }));
  const setChk = (k) => (e) => setData((d) => ({ ...d, [k]: e.target.checked }));
  const next = () => setStep((s) => Math.min(s + 1, 4));
  const back = () => setStep((s) => Math.max(s - 1, 0));

  if (step === 4) return <WizardShell step={3}><Success data={data} /></WizardShell>;

  return (
    <WizardShell step={step}>
      {step === 0 && (
        <Card padding="lg" elevation="sm">
          <StepHeading kicker="Step 1 of 4" title="Your details" sub="We’ll email your certificate here and create your account." />
          <div style={{ display: "grid", gap: 18 }}>
            <Field label="Full name" placeholder="Eleanor Hargreaves" value={data.name} onChange={set("name")} required />
            <Field label="Email address" type="email" placeholder="you@example.co.uk" value={data.email} onChange={set("email")} required hint="Your certificate PDF is sent to this address." />
          </div>
          <Footer canBack={false} onNext={next} />
        </Card>
      )}

      {step === 1 && (
        <Card padding="lg" elevation="sm">
          <StepHeading kicker="Step 2 of 4" title="Your property" sub="The address that appears on your certificate." />
          <div style={{ display: "grid", gap: 18 }}>
            <Field label="Address line" placeholder="14 Rodwell Avenue" value={data.line1} onChange={set("line1")} required />
            <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(150px, 1fr))", gap: 18 }}>
              <Field label="Town / city" placeholder="Weymouth" value={data.town} onChange={set("town")} required />
              <Field label="Postcode" placeholder="DT4 8QT" value={data.postcode} onChange={set("postcode")} required />
            </div>
            <Select label="Property type" value={data.propType} onChange={set("propType")} options={["House", "Flat", "Bungalow", "Other"]} />
          </div>
          <Footer onBack={back} onNext={next} />
        </Card>
      )}

      {step === 2 && (
        <Card padding="lg" elevation="sm">
          <StepHeading kicker="Step 3 of 4" title="Your declaration" sub="This is the statement recorded on your certificate." />
          <Callout tone="neutral" style={{ marginBottom: 22 }}>
            I do not consent to drones recording identifiable footage, images, audio or personal data of me, my household, visitors or private residential spaces at the property above.
          </Callout>
          <div style={{ display: "grid", gap: 16 }}>
            <Checkbox checked={data.declare} onChange={setChk("declare")} label="I make this privacy declaration" description="It will be time-stamped with today’s date and time." />
            <Checkbox checked={data.terms} onChange={setChk("terms")} label="I understand this certificate is not legally binding" description="It does not create a no-fly zone or override UK aviation rules." />
          </div>
          <Footer onBack={back} onNext={next} nextLabel="Continue to payment" />
        </Card>
      )}

      {step === 3 && (
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(260px, 1fr))", gap: 22, alignItems: "start" }}>
          <Card padding="lg" elevation="sm">
            <StepHeading kicker="Step 4 of 4" title="Payment" />
            <div style={{ display: "grid", gap: 18 }}>
              <Field label="Card number" placeholder="1234 5678 9012 3456" prefix={<Icon name="credit-card" size={16} color="var(--text-muted)" />} />
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18 }}>
                <Field label="Expiry" placeholder="MM / YY" />
                <Field label="CVC" placeholder="123" />
              </div>
              <Field label="Name on card" placeholder={data.name || "Eleanor Hargreaves"} />
            </div>
            <Footer onBack={back} onNext={next} nextLabel="Pay £14.99" />
          </Card>
          <Card tone="cream" padding="lg" elevation="sm">
            <div className="eyebrow" style={{ marginBottom: 14 }}>Order summary</div>
            <Row label="Drone Privacy Certificate" value="£14.99" />
            <Row label={data.postcode || "Your property"} muted />
            <div style={{ height: 1, background: "var(--border-cream)", margin: "14px 0" }} />
            <Row label="Total" value="£14.99" bold />
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 16, fontFamily: "var(--font-ui)", fontSize: 12.5, color: "var(--text-muted)" }}>
              <Icon name="shield-check" size={15} color="var(--success)" />Emailed instantly after payment
            </div>
          </Card>
        </div>
      )}
    </WizardShell>
  );
}

function Row({ label, value, bold, muted }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", padding: "4px 0", fontFamily: "var(--font-ui)", fontSize: bold ? 18 : 14.5, fontWeight: bold ? 700 : 500, color: muted ? "var(--text-muted)" : "var(--text-primary)" }}>
      <span>{label}</span>{value && <span style={{ fontFamily: bold ? "var(--font-display)" : "var(--font-ui)" }}>{value}</span>}
    </div>
  );
}

function Success({ data }) {
  return (
    <Card padding="lg" elevation="md" style={{ textAlign: "center" }}>
      <div style={{ display: "flex", justifyContent: "center", marginBottom: 22 }}><Seal size={120} refText="MAS" /></div>
      <Badge tone="success" dot style={{ marginBottom: 16 }}>Certificate issued</Badge>
      <h1 style={{ fontSize: 32, letterSpacing: "-0.02em", marginBottom: 12 }}>You’re on record</h1>
      <p style={{ fontSize: 16.5, lineHeight: 1.6, color: "var(--text-secondary)", maxWidth: 440, margin: "0 auto 26px" }}>
        We’ve emailed your certificate to <strong style={{ color: "var(--text-primary)" }}>{data.email || "your inbox"}</strong>. You can download it any time from your account.
      </p>
      <div style={{ display: "flex", flexWrap: "wrap", gap: 12, justifyContent: "center" }}>
        <Button variant="primary" size="lg" iconLeft={<Icon name="download" size={18} color="#fff" />} onClick={() => { window.location.href = "../certificate/index.html"; }}>View certificate</Button>
        <Button variant="secondary" size="lg" onClick={() => { window.location.href = "../account/index.html"; }}>Go to my account</Button>
      </div>
    </Card>
  );
}
window.PurchaseWizard = PurchaseWizard;
