const Field = ({ label, hint, error, children, required }) => (
  <label className="block">
    <div className="flex items-baseline justify-between mb-1.5">
      <span className="text-sm font-medium text-ink-900">{label}{required ? <span className="text-brand-600 ml-0.5">*</span> : null}</span>
      {hint ? <span className="text-xs text-ink-400">{hint}</span> : null}
    </div>
    {children}
    {error ? <div className="mt-1 text-xs text-brand-600">{error}</div> : null}
  </label>
);

const RadioCard = ({ active, onClick, icon, title, subtitle }) => (
  <button
    type="button"
    onClick={onClick}
    className={`text-left p-3 sm:p-4 rounded-2xl border-2 transition w-full active:scale-95 ${
      active ? 'border-brand-500 bg-brand-50' : 'border-paper-200 bg-white hover:border-brand-200'
    }`}
  >
    <div className="flex items-start gap-2.5 sm:gap-3">
      <div className={`w-8 h-8 sm:w-9 sm:h-9 rounded-xl flex items-center justify-center shrink-0 ${active ? 'bg-brand-500 text-white' : 'bg-paper-100 text-ink-700'}`}>
        <Icon name={icon} size={17} />
      </div>
      <div className="flex-1 min-w-0">
        <div className="font-semibold text-ink-900 text-[13px] sm:text-sm">{title}</div>
        <div className="text-[11px] sm:text-xs text-ink-500 mt-0.5 leading-snug">{subtitle}</div>
      </div>
      <div className={`w-5 h-5 rounded-full border-2 flex items-center justify-center shrink-0 mt-0.5 ${active ? 'border-brand-500 bg-brand-500' : 'border-paper-200 bg-white'}`}>
        {active ? <Icon name="check" size={11} className="text-white" /> : null}
      </div>
    </div>
  </button>
);

const Checkout = ({ onCancel, onSuccess }) => {
  const { cart, cartTotal, submitOrder } = useStore();
  const [form, setForm] = useState({
    name: '', city: '', team: '', contact: '', comment: '', delivery: 'office', agree: false, pdAgree: false,
  });
  const [errors, setErrors] = useState({});
  const [submitting, setSubmitting] = useState(false);
  const [serverError, setServerError] = useState('');

  const update = (k, v) => setForm((f) => ({ ...f, [k]: v }));

  const validate = () => {
    const e = {};
    if (!form.name.trim()) e.name = 'Укажите ФИО';
    if (!form.city) e.city = 'Выберите город';
    if (!form.team) e.team = 'Выберите команду';
    if (!form.contact.trim()) e.contact = 'Укажите email или Telegram';
    if (!form.agree) e.agree = 'Подтвердите, что вы понимаете условия';
    if (!form.pdAgree) e.pdAgree = 'Необходимо согласие на обработку персональных данных';
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!validate()) return;
    setSubmitting(true);
    setServerError('');
    try {
      const order = await submitOrder({
        customer: { name: form.name, city: form.city, team: form.team, contact: form.contact },
        delivery: form.delivery,
        comment: form.comment,
      });
      onSuccess(order);
    } catch (err) {
      setServerError('Ошибка отправки. Попробуйте ещё раз.');
      setSubmitting(false);
    }
  };

  if (cart.length === 0) {
    return (
      <div className="max-w-3xl mx-auto px-4 md:px-8 py-16">
        <EmptyState icon="bag" title="Сначала добавьте товары" subtitle="В корзине пусто — оформлять пока нечего."
          action={<button className="btn-primary" onClick={onCancel}>Перейти к каталогу</button>} />
      </div>
    );
  }

  return (
    <>
      <div className="max-w-6xl mx-auto px-4 md:px-8 py-5 sm:py-8 md:py-12 pb-32 lg:pb-12">
        <button onClick={onCancel} className="text-sm font-medium text-ink-500 hover:text-ink-900 inline-flex items-center gap-1.5 mb-4">
          <Icon name="arrowLeft" size={14} /> Назад к корзине
        </button>
        <h1 className="font-display font-bold text-2xl sm:text-3xl md:text-4xl text-ink-900 tracking-tight">Оформление заявки</h1>
        <p className="text-ink-500 text-sm sm:text-base mt-2 max-w-xl">Заполните контакты — продавец или организатор свяжется с вами для подтверждения.</p>

        <form onSubmit={handleSubmit} className="mt-6 sm:mt-8 grid lg:grid-cols-[1fr_380px] gap-5 sm:gap-6 lg:gap-10 items-start">
          <div className="space-y-4 sm:space-y-6">

            {/* Покупатель */}
            <section className="bg-white rounded-2xl border border-paper-200 p-4 sm:p-5 md:p-6">
              <div className="font-display font-semibold text-base sm:text-lg text-ink-900 mb-4 sm:mb-5">Покупатель</div>
              <div className="grid sm:grid-cols-2 gap-3 sm:gap-4">
                <div className="sm:col-span-2">
                  <Field label="ФИО" required error={errors.name}>
                    <input className="input" placeholder="Иванова Анна Сергеевна" value={form.name} onChange={(e) => update('name', e.target.value)} />
                  </Field>
                </div>
                <Field label="Город" required error={errors.city}>
                  <div className="relative">
                    <select className="input appearance-none pr-10" value={form.city} onChange={(e) => update('city', e.target.value)}>
                      <option value="">Выберите город</option>
                      {window.DATA.CITIES.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
                    </select>
                    <Icon name="chevronDown" size={16} className="absolute right-3 top-1/2 -translate-y-1/2 text-ink-400 pointer-events-none" />
                  </div>
                </Field>
                <Field label="Отдел / команда" required error={errors.team}>
                  <div className="relative">
                    <select className="input appearance-none pr-10" value={form.team} onChange={(e) => update('team', e.target.value)}>
                      <option value="">Выберите команду</option>
                      {window.DATA.TEAMS.map((t) => <option key={t.id} value={t.id}>{t.name}</option>)}
                    </select>
                    <Icon name="chevronDown" size={16} className="absolute right-3 top-1/2 -translate-y-1/2 text-ink-400 pointer-events-none" />
                  </div>
                </Field>
                <div className="sm:col-span-2">
                  <Field label="Email или Telegram" required error={errors.contact}>
                    <input className="input" placeholder="@username или name@company.ru" value={form.contact} onChange={(e) => update('contact', e.target.value)} />
                  </Field>
                </div>
                <div className="sm:col-span-2">
                  <Field label="Комментарий к заказу" hint="необязательно">
                    <textarea rows={3} className="input resize-none" placeholder="Например: «можно красивую упаковку» или «заберу в пятницу»" value={form.comment} onChange={(e) => update('comment', e.target.value)} />
                  </Field>
                </div>
              </div>
            </section>

            {/* Способ получения */}
            <section className="bg-white rounded-2xl border border-paper-200 p-4 sm:p-5 md:p-6">
              <div className="font-display font-semibold text-base sm:text-lg text-ink-900 mb-4 sm:mb-5">Способ получения</div>
              <div className="grid grid-cols-1 sm:grid-cols-3 gap-2.5 sm:gap-3">
                <RadioCard active={form.delivery === 'office'}     onClick={() => update('delivery', 'office')}     icon="bag"   title="Заберу в офисе"  subtitle="Договоритесь о времени с продавцом" />
                <RadioCard active={form.delivery === 'colleagues'} onClick={() => update('delivery', 'colleagues')} icon="users" title="Через коллег"     subtitle="Передача через того, кто едет в офис" />
                <RadioCard active={form.delivery === 'arrange'}    onClick={() => update('delivery', 'arrange')}    icon="phone" title="Связаться"        subtitle="Уточним детали в переписке" />
              </div>
            </section>

            {/* Согласие об условиях */}
            <section className={`bg-white rounded-2xl border p-4 sm:p-5 md:p-6 transition ${errors.agree ? 'border-brand-500' : 'border-paper-200'}`}>
              <label className="flex items-start gap-3 cursor-pointer">
                <span className={`w-5 h-5 rounded-md border-2 flex items-center justify-center shrink-0 mt-0.5 transition ${form.agree ? 'bg-brand-500 border-brand-500' : 'border-paper-200 bg-white'}`}>
                  {form.agree ? <Icon name="check" size={12} className="text-white" /> : null}
                </span>
                <input type="checkbox" checked={form.agree} onChange={(e) => update('agree', e.target.checked)} className="sr-only" />
                <span className="text-sm text-ink-700 leading-relaxed">
                  Я понимаю, что это заявка <span className="font-semibold">без онлайн-оплаты</span>. Продавец или организатор ярмарки свяжется со мной для подтверждения заказа.
                </span>
              </label>
              {errors.agree ? <div className="mt-2 text-xs text-brand-600 ml-8">{errors.agree}</div> : null}
            </section>

            {/* Согласие 152-ФЗ */}
            <section className={`bg-white rounded-2xl border p-4 sm:p-5 md:p-6 transition ${errors.pdAgree ? 'border-brand-500' : 'border-paper-200'}`}>
              <label className="flex items-start gap-3 cursor-pointer">
                <span className={`w-5 h-5 rounded-md border-2 flex items-center justify-center shrink-0 mt-0.5 transition ${form.pdAgree ? 'bg-brand-500 border-brand-500' : 'border-paper-200 bg-white'}`}>
                  {form.pdAgree ? <Icon name="check" size={12} className="text-white" /> : null}
                </span>
                <input type="checkbox" checked={form.pdAgree} onChange={(e) => update('pdAgree', e.target.checked)} className="sr-only" />
                <span className="text-sm text-ink-700 leading-relaxed">
                  Я даю согласие на обработку моих персональных данных в соответствии с{' '}
                  <a href="/legal/privacy.html" target="_blank" className="text-brand-700 underline">Политикой конфиденциальности</a>{' '}
                  в целях обработки заявки (ФЗ № 152-ФЗ).
                </span>
              </label>
              {errors.pdAgree ? <div className="mt-2 text-xs text-brand-600 ml-8">{errors.pdAgree}</div> : null}
            </section>

            {serverError && (
              <div className="rounded-xl bg-red-50 border border-red-200 p-4 text-sm text-red-700">{serverError}</div>
            )}
          </div>

          {/* Summary sidebar — только десктоп */}
          <aside className="hidden lg:block bg-white rounded-2xl border border-paper-200 p-5 md:p-6 lg:sticky lg:top-24">
            <div className="font-display font-semibold text-lg text-ink-900 mb-4">Ваша заявка</div>
            <div className="max-h-72 overflow-y-auto -mr-2 pr-2 space-y-3">
              {cart.map((item) => {
                const p = window.DATA.productById(item.productId);
                if (!p) return null;
                return (
                  <div key={p.id} className="flex gap-3 items-center">
                    <div className="w-12 h-12 rounded-lg overflow-hidden shrink-0"><ProductVisual product={p} /></div>
                    <div className="flex-1 min-w-0">
                      <div className="text-sm font-medium text-ink-900 leading-tight truncate">{p.title}</div>
                      <div className="text-xs text-ink-500 mt-0.5">{item.qty} × {fmtPrice(p.price)}</div>
                    </div>
                    <div className="text-sm font-semibold tabular-nums">{fmtPrice(p.price * item.qty)}</div>
                  </div>
                );
              })}
            </div>
            <div className="border-t border-paper-100 mt-4 pt-4 space-y-2">
              <div className="flex justify-between text-sm">
                <span className="text-ink-500">Товаров</span>
                <span className="font-medium tabular-nums">{cart.reduce((s, i) => s + i.qty, 0)}</span>
              </div>
              <div className="flex justify-between items-baseline pt-1">
                <span className="text-ink-500">Итого</span>
                <span className="font-display font-bold text-2xl text-ink-900 tabular-nums">{fmtPrice(cartTotal)}</span>
              </div>
            </div>
            <div className="mt-4 bg-brand-50 rounded-xl p-3 flex items-start gap-2.5 text-xs text-brand-800 leading-snug">
              <Icon name="handshake" size={14} className="shrink-0 mt-0.5 text-brand-600" />
              <div>Оплата на сайте не проводится — после оформления с вами свяжется продавец.</div>
            </div>
            <button type="submit" disabled={submitting} className="btn-primary w-full mt-5 inline-flex items-center justify-center gap-2 text-base">
              {submitting ? 'Отправляем…' : <><span>Оставить заявку</span> <Icon name="arrowRight" size={18} /></>}
            </button>
          </aside>
        </form>
      </div>

      {/* Mobile sticky bottom bar */}
      <div className="fixed bottom-0 left-0 right-0 lg:hidden bg-white border-t border-paper-200 z-30 safe-bottom">
        <div className="px-4 pt-3 pb-1">
          <div className="flex items-center justify-between mb-3">
            <div className="text-sm text-ink-500">
              {cart.reduce((s, i) => s + i.qty, 0)} поз. · {fmtPrice(cartTotal)}
            </div>
            {serverError && <div className="text-xs text-red-600">Ошибка отправки</div>}
          </div>
          <button
            type="button"
            disabled={submitting}
            onClick={handleSubmit}
            className="btn-primary w-full inline-flex items-center justify-center gap-2 text-base"
          >
            {submitting ? 'Отправляем…' : <><span>Оставить заявку</span> <Icon name="arrowRight" size={18} /></>}
          </button>
        </div>
      </div>
    </>
  );
};

const SuccessScreen = ({ order, onBack }) => {
  if (!order) return null;
  return (
    <div className="max-w-3xl mx-auto px-4 md:px-8 py-10 sm:py-12 md:py-20">
      <div className="bg-white rounded-3xl border border-paper-200 p-5 sm:p-6 md:p-10 text-center shadow-card relative overflow-hidden">
        <div className="absolute inset-x-0 top-0 h-32 bg-gradient-to-b from-brand-50 to-transparent" />
        <div className="relative">
          <div className="w-16 h-16 sm:w-20 sm:h-20 rounded-3xl bg-brand-500 text-white flex items-center justify-center mx-auto shadow-pop">
            <Icon name="check" size={30} strokeWidth={2.5} />
          </div>
          <h1 className="font-display font-bold text-2xl sm:text-3xl md:text-4xl text-ink-900 mt-5 sm:mt-6 tracking-tight">Заявка оформлена!</h1>
          <p className="text-ink-500 mt-3 max-w-md mx-auto text-sm sm:text-base">С вами свяжутся для подтверждения заказа и согласования способа передачи.</p>
          <div className="mt-6 sm:mt-8 inline-flex items-center gap-3 px-5 py-3 rounded-2xl bg-paper-100">
            <span className="text-sm text-ink-500">Номер заявки</span>
            <span className="font-display font-bold text-lg text-ink-900 tracking-wide">{order.id}</span>
          </div>
          <div className="mt-6 sm:mt-8 grid grid-cols-1 sm:grid-cols-3 gap-2.5 sm:gap-3 text-left max-w-xl mx-auto">
            <div className="rounded-xl bg-paper-50 p-4">
              <div className="text-xs text-ink-500 uppercase tracking-wider mb-1">Когда</div>
              <div className="font-medium text-ink-900 text-sm">{order.createdAt}</div>
            </div>
            <div className="rounded-xl bg-paper-50 p-4">
              <div className="text-xs text-ink-500 uppercase tracking-wider mb-1">Покупатель</div>
              <div className="font-medium text-ink-900 text-sm">{order.customer?.name}</div>
            </div>
            <div className="rounded-xl bg-paper-50 p-4">
              <div className="text-xs text-ink-500 uppercase tracking-wider mb-1">Связь</div>
              <div className="font-medium text-ink-900 text-sm break-all">{order.customer?.contact}</div>
            </div>
          </div>
          <div className="mt-6 sm:mt-8">
            <button onClick={onBack} className="btn-primary inline-flex items-center gap-2">
              <Icon name="arrowLeft" size={16} /> Вернуться в каталог
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { Checkout, SuccessScreen });
