const PLAN_INFO = {
  single: { label: 'Pay per can', water: 120, detail: '2 cans at ₹60 each' },
  monthly: { label: 'Monthly refills', water: 1500, detail: '30 cans over 30 days' },
  biz: { label: 'Business monthly', water: 1500, detail: '30 cans, GST invoice' },
  custom: { label: 'Custom schedule', detail: '₹60 a can, on your dates' },
};
const SLOTS = ['7–9 am', '9–11 am', '4–6 pm', '6–8 pm'];
const AREAS = ['Thane', 'Mira Bhayandar', 'Dahisar', 'Borivali', 'Kandivali'];
const PHONE_RE = /^(?:\+?91)?[6-9]\d{9}$/;
const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

function StepHead({ n, title, lead }) {
  return <div className="step-head">
    <span className="step-num" aria-hidden="true">{n}</span>
    <div>
      <h2 className="s-display s-h3"><span className="s-sr">Step {n}: </span>{title}</h2>
      {lead && <p className="s-body" style={{ marginTop: 6 }}>{lead}</p>}
    </div>
  </div>;
}

function Plans({ go, business, intent }) {
  const { Input, Select, Checkbox, Dialog, Toast, Icon, OrderPlanner } = window.DesignSystem_f6a2e7;
  const intentPlan = intent && intent.value;
  const [plan, setPlan] = React.useState(() => intentPlan || (business ? 'biz' : 'monthly'));
  const [schedule, setSchedule] = React.useState({});
  const [disp, setDisp] = React.useState(false);
  const [form, setForm] = React.useState({ name: '', phone: '', area: '', address: '', slot: '' });
  const [errors, setErrors] = React.useState({});
  const [done, setDone] = React.useState(false);
  const [toast, setToast] = React.useState(false);

  const smooth = () => (prefersReducedMotion() ? 'auto' : 'smooth');
  const scrollToId = id => { const el = document.getElementById(id); if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 96, behavior: smooth() }); };

  React.useEffect(() => {
    setPlan(p => (business ? (p === 'custom' ? p : 'biz') : (p === 'biz' ? 'monthly' : p)));
  }, [business]);
  React.useEffect(() => {
    if (!intentPlan) return;
    setPlan(intentPlan);
    const t = setTimeout(() => scrollToId('order'), 60);
    return () => clearTimeout(t);
  }, [intent]);

  const custom = plan === 'custom';
  const dates = Object.keys(schedule).sort();
  const cans = Object.values(schedule).reduce((a, b) => a + b, 0);
  const water = custom ? cans * 60 : PLAN_INFO[plan].water;
  const total = water + 200 + (disp ? 1200 : 0);
  const fmt = k => { const [, m, dd] = k.split('-'); return Number(dd) + ' ' + MONTHS[Number(m) - 1]; };
  const first = dates.length ? fmt(dates[0]) : null;
  const span = dates.length > 1 ? fmt(dates[0]) + ' – ' + fmt(dates[dates.length - 1]) : first;
  const rupees = n => '₹' + n.toLocaleString('en-IN');
  const hasErrors = Object.values(errors).some(Boolean);

  const clearError = k => setErrors(er => (er[k] ? { ...er, [k]: undefined } : er));
  const set = k => e => { const v = e.target.value; setForm(f => ({ ...f, [k]: v })); clearError(k); };
  const updateSchedule = next => { setSchedule(next); if (Object.keys(next).length) clearError('dates'); };
  const selectAndContinue = p => ({ onClick: e => { e.stopPropagation(); setPlan(p); scrollToId('order'); } });

  const validate = () => {
    const e = {};
    if (custom && dates.length === 0) e.dates = 'Pick at least one delivery date.';
    if (!form.name.trim()) e.name = business ? 'Add your business name.' : 'Please tell us your name.';
    const phone = form.phone.replace(/[\s-]/g, '');
    if (!phone) e.phone = 'Add a phone number so we can confirm your slot.';
    else if (!PHONE_RE.test(phone)) e.phone = 'Enter a 10-digit mobile number.';
    if (!form.area) e.area = 'Choose your delivery area.';
    if (!form.address.trim()) e.address = 'Add your flat, building and landmark.';
    if (!form.slot) e.slot = 'Choose a delivery slot.';
    setErrors(e);
    return Object.keys(e);
  };
  const placeOrder = () => {
    const missing = validate();
    if (missing.length) {
      const field = document.querySelector('[data-field="' + missing[0] + '"]');
      if (field) {
        field.scrollIntoView({ behavior: smooth(), block: 'center' });
        const control = field.querySelector('input, select, button');
        if (control) control.focus({ preventScroll: true });
      }
      return;
    }
    setDone(true);
  };
  const finish = () => { setDone(false); setToast(true); setTimeout(() => setToast(false), 4000); };

  const tile = (key, props) => <PlanTile selectable onSelect={() => setPlan(key)} selected={plan === key} cta={plan === key ? 'Continue' : 'Select'} icon={plan === key ? 'arrow-down' : 'plus'} action={selectAndContinue(key)} {...props} />;
  const fieldError = k => errors[k] && <p className="s-field-error"><Icon name="alert-circle" size={15} />{errors[k]}</p>;

  return <main>
    <PageHero
      center
      tag={business ? 'For business' : 'Plans'}
      title={business ? 'Water for cafés, kitchens and offices.' : 'Pay per can, refill monthly, or pick your dates.'}
      lead="Same water, same 12-hour promise. A ₹200 refundable deposit covers your first can."
    >
      <div className="hx-rise" style={{ '--dl': '.75s', marginTop: 32 }}><Segmented label="Plan type" items={[{ value: 'home', label: 'For home' }, { value: 'biz', label: 'For business' }]} value={business ? 'biz' : 'home'} onChange={v => go(v === 'biz' ? 'business' : 'plans', null, { keepScroll: true })} /></div>
    </PageHero>

    <section className="s-wrap s-sec-t" id="step-plan">
      <StepHead n={1} title="Choose a plan" lead="Tap a plan to select it. You can change it any time before you place the order." />
      <div className="g3" style={{ marginTop: 28, alignItems: 'stretch' }}>
        {!business && <Reveal>{tile('single', { name: 'Pay per can', price: '₹60', period: 'per can', note: 'Minimum 2 cans per order · ₹200 refundable deposit', features: ['Delivered within 12 hours', 'Empty cans collected on next delivery', 'No commitment'] })}</Reveal>}
        {!business && <Reveal delay={90}>{tile('monthly', { featured: true, badge: 'Most popular', name: 'Monthly refills', price: '₹1,500', period: '/ 30 days', note: 'One can a day, or spread as you like · ₹200 refundable deposit', features: ['30 refills, scheduled or on demand', 'Priority morning slots', 'Pause or cancel any time'] })}</Reveal>}
        {business && <Reveal>{tile('biz', { featured: true, badge: 'For cafés', name: 'Business monthly', price: '₹1,500', period: '/ 30 cans', note: 'Fixed morning slot, one GST invoice · ₹200 refundable deposit', features: ['30 cans a month, top up any time at ₹60', 'Dedicated delivery slot before opening', 'GST invoice, monthly billing'] })}</Reveal>}
        {business && <Reveal delay={90} className="s-card" style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <h3 className="s-h3">Need more than 30?</h3>
          <p className="s-body">Restaurants and offices ordering 40+ cans a week get a custom rate and a second slot. Tell us your volume and we'll call back the same day.</p>
          <div className="g2" style={{ marginTop: 'auto' }}>
            <div className="s-card s-card--brand" style={{ padding: 20 }}><Stat onBrand value={90} suffix="+" label="Cafés served" /></div>
            <div className="s-card s-card--white" style={{ padding: 20 }}><Stat value={0} label="Missed days, on average" /></div>
          </div>
          <Cta variant="soft" noIcon {...routeLink(go, 'contact')}>Contact us</Cta>
        </Reveal>}
        <Reveal delay={180}>{tile('custom', { name: 'Custom schedule', price: '₹60', period: 'per can', note: 'Only the dates you pick · ₹200 refundable deposit', features: ['Any dates, across any month', 'From 2 cans a date, up as you need', 'Patterns: weekdays, alternate days, every Monday'] })}</Reveal>
      </div>
    </section>

    <section className="s-wrap s-sec-t" id="order">
      <div className="order-grid">
        <div className="order-main">
          {custom && <div className="order-step" data-field="dates">
            <StepHead n={2} title="Pick your dates" lead="Tap any date to schedule a delivery, then set how many cans that day needs. Mix weeks and months freely." />
            <div className="s-card order-card">
              <div className="order-planner"><OrderPlanner value={schedule} onChange={updateSchedule} defaultQty={2} /></div>
              {fieldError('dates')}
              <p className="s-note order-hint"><Icon name="info" size={16} color="var(--logo-blue)" />Dates before today are closed. Order before 6 pm for a next-morning first delivery.</p>
            </div>
          </div>}

          <div className="order-step">
            <StepHead n={custom ? 3 : 2} title="Delivery details" lead="We'll confirm your slot by SMS." />
            <div className="s-card order-card">
              <div className="s-form">
                <div className="g2">
                  <div data-field="name"><Input label={business ? 'Business name' : 'Your name'} icon={business ? 'store' : 'user'} value={form.name} onChange={set('name')} required error={errors.name} /></div>
                  <div data-field="phone"><Input label="Phone" type="tel" icon="phone" placeholder="10-digit mobile" value={form.phone} onChange={set('phone')} required error={errors.phone} /></div>
                </div>
                <div data-field="area"><Select label="Delivery area" placeholder="Choose your area" options={AREAS} value={form.area} onChange={set('area')} />{fieldError('area')}</div>
                <div data-field="address"><Input label="Address" icon="map-pin" placeholder="Flat, building, landmark" value={form.address} onChange={set('address')} required error={errors.address} /></div>
                <div data-field="slot"><Select label="Preferred slot" placeholder="Choose a slot" options={SLOTS} value={form.slot} onChange={set('slot')} />{fieldError('slot')}</div>
                <div className="s-choice"><Checkbox label="Add a dispenser" description="₹1,200 one-time, delivered with the first can" checked={disp} onChange={e => setDisp(e.target.checked)} /></div>
              </div>
            </div>
          </div>
        </div>

        <aside className="order-aside" aria-label="Order summary">
          <div className="receipt">
            <div>
              <div className="receipt-head">
                <div><div className="pp-kicker">Receipt · {business ? 'Business' : 'Home'}</div><h2 className="s-h4">Your order</h2></div>
                <button type="button" className="s-link" onClick={() => scrollToId('step-plan')}>Change plan</button>
              </div>
              <div className="sum-rows">
                <div className="sum-row"><span>{PLAN_INFO[plan].label}<small>{custom ? (cans ? cans + ' cans at ₹60' : PLAN_INFO.custom.detail) : PLAN_INFO[plan].detail}</small></span><span>{rupees(water)}</span></div>
                {custom && <div className="sum-row"><span>Deliveries</span><span>{dates.length ? dates.length + ' · ' + span : '—'}</span></div>}
                <div className="sum-row"><span>Slot</span><span>{form.slot || '—'}</span></div>
                {disp && <div className="sum-row"><span>Dispenser</span><span>₹1,200</span></div>}
                <div className="sum-row"><span>Refundable deposit</span><span>₹200</span></div>
                <div className="sum-total"><span>Due today</span><span>{rupees(total)}</span></div>
              </div>
              {hasErrors && <p className="order-alert" role="alert"><Icon name="alert-circle" size={18} />Add the missing details to place your order.</p>}
              <div style={{ marginTop: 20 }}><Cta full icon="check" onClick={placeOrder}>Place order</Cta></div>
              <p className="order-fine">Pay on delivery or UPI. Skip or move any single date later at no cost.</p>
              <Barcode value={'AQ-' + plan.toUpperCase() + '-' + rupees(total).replace(/\D/g, '')} />
            </div>
          </div>
        </aside>
      </div>
    </section>

    <section className="s-wrap s-sec-t">
      <SectionHead tag="Good to know" title="Deposits, dates and refills." />
      <div style={{ marginTop: 48 }}>
        <FaqGrid items={[{ q: 'Can I order for dates in two different months?', a: 'Yes. Move the calendar forward and keep picking; everything you select lands in one order with one total.' }, { q: 'Can I get a different number of cans on different days?', a: 'Yes. Each scheduled date has its own quantity — five cans on Monday and two on Friday is fine.' }, { q: 'What if I need to skip one date?', a: 'Remove it from the list before ordering, or tell us later. Skipping a single delivery costs nothing.' }, { q: 'Why is there a ₹200 deposit?', a: 'It covers the can while it is with you. You get it back when you return the can or stop the plan.' }, { q: 'Can I pause monthly refills?', a: 'Yes, from a single message. Unused refills carry over for up to 30 days.' }]} />
      </div>
    </section>

    <Dialog open={done} onClose={finish} title="Order placed" description={custom ? "We've booked " + dates.length + ' deliveries (' + cans + ' cans) in the ' + form.slot + " slot. We'll message " + form.phone + ' the evening before each one.' : 'Your first delivery is booked for the ' + form.slot + " slot. We'll message " + form.phone + " when it's on its way."} footer={<Cta icon="check" onClick={finish}>Done</Cta>}>
      <p className="order-proto"><Icon name="info" size={18} />Prototype only; no order was sent.</p>
    </Dialog>
    {toast && <div style={{ position: 'fixed', right: 24, bottom: 24, zIndex: 60 }}><Toast tone="success" title="Order confirmed" message={custom ? 'First delivery on ' + (first || 'your first date') + '.' : 'First delivery in your ' + form.slot + ' slot.'} onClose={() => setToast(false)} /></div>}
  </main>;
}
Object.assign(window, { Plans });
