const { useState, useEffect, useMemo, useRef } = React;

function CheckoutInfo({ cart, info, setInfo, onBack, onNext }) {
  const [errors, setErrors] = useState({});

  const validate = () => {
    const e = {};
    if (!info.email || !/\S+@\S+\.\S+/.test(info.email)) e.email = 'メールアドレスを正しく入力してください';
    if (!info.parentName) e.parentName = '保護者氏名を入力してください';
    if (!info.parentKana) e.parentKana = 'ふりがなを入力してください';
    if (!info.phone || !/^\d{10,11}$/.test(info.phone.replace(/-/g, ''))) e.phone = '携帯電話番号を入力してください（例：09011111111）';
    if (!info.childName) e.childName = '児童氏名を入力してください';
    if (!info.childClass) e.childClass = 'クラスを選択してください';
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const handleNext = () => {
    if (validate()) onNext();
  };

  return (
    <div className="checkout-page">
      <CheckoutSteps step={2} />
      <div className="co-grid">
        <main className="co-main">
          <header className="co-header">
            <div className="co-eyebrow">STEP 2 of 3</div>
            <h1>保護者情報のご入力</h1>
            <p>お受け取りのご連絡に使用します。正確にご記入ください。</p>
          </header>

          <div className="form-stack">
            <Field label="メールアドレス" required error={errors.email}>
              <input
                type="email"
                value={info.email}
                onChange={e => setInfo({ ...info, email: e.target.value })}
                placeholder="example@email.com"
              />
            </Field>

            <div className="form-row">
              <Field label="保護者氏名" required error={errors.parentName}>
                <input
                  type="text"
                  value={info.parentName}
                  onChange={e => setInfo({ ...info, parentName: e.target.value })}
                  placeholder="等々力 太郎"
                />
              </Field>
              <Field label="ふりがな" required error={errors.parentKana}>
                <input
                  type="text"
                  value={info.parentKana}
                  onChange={e => setInfo({ ...info, parentKana: e.target.value })}
                  placeholder="とどろき たろう"
                />
              </Field>
            </div>

            <Field label="携帯電話番号" required error={errors.phone} hint="ハイフンなし／例：09011111111">
              <input
                type="tel"
                value={info.phone}
                onChange={e => setInfo({ ...info, phone: e.target.value })}
                placeholder="09011111111"
              />
            </Field>

            <div className="notice">
              <div className="notice-icon">
                <svg viewBox="0 0 24 24" width="18" height="18"><circle cx="12" cy="12" r="10" fill="none" stroke="currentColor" strokeWidth="1.5"/><text x="12" y="16" textAnchor="middle" fontSize="12" fontWeight="700" fill="currentColor">!</text></svg>
              </div>
              <div>
                <strong>ご兄弟がいる場合</strong> お子様のお名前は<em>一番下のお子様</em>のお名前をご記入ください。
              </div>
            </div>

            <div className="form-row">
              <Field label="児童氏名" required error={errors.childName} hint="一番下のお子様">
                <input
                  type="text"
                  value={info.childName}
                  onChange={e => setInfo({ ...info, childName: e.target.value })}
                  placeholder="等々力 花子"
                />
              </Field>
              <Field label="クラス" required error={errors.childClass}>
                <select
                  value={info.childClass}
                  onChange={e => setInfo({ ...info, childClass: e.target.value })}
                >
                  <option value="">選択してください</option>
                  {window.CLASS_OPTIONS.map(c => <option key={c} value={c}>{c} 組</option>)}
                </select>
              </Field>
            </div>
          </div>

          <div className="co-actions">
            <button className="btn-ghost" onClick={onBack}>← カートに戻る</button>
            <button className="btn-primary" onClick={handleNext}>内容確認へ進む →</button>
          </div>
        </main>

        <aside className="co-summary">
          <OrderSummary cart={cart} />
        </aside>
      </div>
    </div>
  );
}

function Field({ label, required, error, hint, children }) {
  return (
    <label className={`field ${error ? 'has-error' : ''}`}>
      <div className="field-label">
        {label} {required && <span className="req">必須</span>}
      </div>
      {children}
      {hint && !error && <div className="field-hint">{hint}</div>}
      {error && <div className="field-error">{error}</div>}
    </label>
  );
}

function OrderSummary({ cart }) {
  const products = window.PRODUCTS;
  const total = cart.reduce((s, it) => s + it.qty * it.unitPrice, 0);
  const count = cart.reduce((s, it) => s + it.qty, 0);

  return (
    <div className="summary-card">
      <div className="sc-head">ご注文内容</div>
      <div className="sc-list">
        {cart.map((it, idx) => {
          const p = products.find(x => x.id === it.productId);
          return (
            <div className="sc-item" key={idx}>
              <div className="sc-thumb"><ProductVisual product={p} size={56} colorKey={it.color} /></div>
              <div className="sc-body">
                <div className="sc-name">{p.code} {p.name}</div>
                <div className="sc-meta">
                  {p.variants.length > 1 && <span>{window.VARIANT_LABELS[it.variant]}</span>}
                  {it.color && <span>{window.VARIANT_LABELS[it.color]}</span>}
                  <span>{it.size}</span>
                  <span>× {it.qty}</span>
                </div>
              </div>
              <div className="sc-price">¥{(it.qty * it.unitPrice).toLocaleString()}</div>
            </div>
          );
        })}
      </div>
      <div className="sc-totals">
        <div className="sc-row"><span>点数</span><span>{count}点</span></div>
        <div className="sc-row big"><span>合計金額</span><span>¥{total.toLocaleString()}</span></div>
      </div>
    </div>
  );
}

function CheckoutSteps({ step }) {
  const steps = ['カート', '保護者情報', '内容確認', '完了'];
  return (
    <div className="checkout-steps">
      {steps.map((s, i) => (
        <React.Fragment key={i}>
          <div className={`step ${i + 1 < step ? 'done' : i + 1 === step ? 'active' : ''}`}>
            <div className="step-dot">{i + 1 < step ? '✓' : i + 1}</div>
            <span>{s}</span>
          </div>
          {i < steps.length - 1 && <div className={`step-line ${i + 1 < step ? 'done' : ''}`}/>}
        </React.Fragment>
      ))}
    </div>
  );
}

window.CheckoutInfo = CheckoutInfo;
window.OrderSummary = OrderSummary;
window.CheckoutSteps = CheckoutSteps;
