/* ============================================================
   payment.jsx — GB Prime Pay installment (ผ่อนชำระ) flow
   ============================================================ */

const INSTALLMENT_PACKAGES = [
  { id: 'pkg10', sessions: 10, discountPct: 5,  label: '10 คาบ' },
  { id: 'pkg20', sessions: 20, discountPct: 10, label: '20 คาบ', popular: true },
  { id: 'pkg30', sessions: 30, discountPct: 15, label: '30 คาบ' },
];

const INSTALLMENT_PLANS = [
  { months: 3,  label: '3 งวด',  minAmount: 3000 },
  { months: 6,  label: '6 งวด',  minAmount: 5000 },
  { months: 10, label: '10 งวด', minAmount: 10000 },
];

function pkgPrice(pricePerSession, sessions, discountPct) {
  return Math.round(pricePerSession * sessions * (1 - discountPct / 100));
}

function monthlyAmt(total, months) {
  return Math.ceil(total / months);
}

function fmt(n) {
  return n.toLocaleString('th-TH');
}

// ── Step components ────────────────────────────────────────────────────────────

function SubjectStep({ courses, selected, onSelect }) {
  const icons = { piano: '♪', vocal: '♫', dance: '✦', drums: '◉', guitar: '♭', acting: '✺' };
  return (
    <div>
      <p className="step-sub">เลือกวิชาที่ต้องการซื้อแพ็กเกจ</p>
      <div className="option-grid">
        {courses.map(c => (
          <button key={c.id}
            className={`option-card ${selected === c.id ? 'selected' : ''}`}
            onClick={() => onSelect(c.id)}>
            <div className="opt-ic">{icons[c.id] || '♪'}</div>
            <div className="opt-name">{c.name}</div>
            <div className="opt-desc">{c.nameEn}</div>
          </button>
        ))}
      </div>
    </div>
  );
}

function PackageStep({ pricePerSession, selected, onSelect }) {
  return (
    <div>
      <p className="step-sub">ซื้อหลายคาบได้ราคาดีกว่า — ส่วนลดสูงสุด 15%</p>
      <div className="option-grid" style={{ gridTemplateColumns: 'repeat(3,1fr)' }}>
        {INSTALLMENT_PACKAGES.map(pkg => {
          const total = pkgPrice(pricePerSession, pkg.sessions, pkg.discountPct);
          return (
            <button key={pkg.id}
              className={`option-card ${selected === pkg.id ? 'selected' : ''}`}
              onClick={() => onSelect(pkg.id)}
              style={{ textAlign: 'center', position: 'relative' }}>
              {pkg.popular && (
                <span className="course-tag" style={{ position: 'absolute', top: 10, right: 10, fontSize: 10, background: 'var(--accent)', color: '#fff', borderColor: 'var(--accent)' }}>แนะนำ</span>
              )}
              <div style={{ fontFamily: 'var(--font-thai-display)', fontSize: 22, fontWeight: 600 }}>{pkg.sessions}</div>
              <div className="opt-desc" style={{ marginBottom: 8 }}>คาบ</div>
              <div style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 18, color: 'var(--accent)' }}>
                ฿{fmt(total)}
              </div>
              <div className="opt-desc">ประหยัด {pkg.discountPct}%</div>
            </button>
          );
        })}
      </div>
    </div>
  );
}

function PlanStep({ totalAmount, selected, onSelect }) {
  return (
    <div>
      <p className="step-sub">เลือกจำนวนงวดที่สะดวก — ยอดรวม ฿{fmt(totalAmount)}</p>
      <div className="option-grid" style={{ gridTemplateColumns: 'repeat(3,1fr)' }}>
        {INSTALLMENT_PLANS.map(plan => {
          const disabled = totalAmount < plan.minAmount;
          const monthly = monthlyAmt(totalAmount, plan.months);
          return (
            <button key={plan.months}
              className={`option-card ${selected === plan.months ? 'selected' : ''} ${disabled ? 'disabled' : ''}`}
              onClick={() => !disabled && onSelect(plan.months)}
              style={{ textAlign: 'center', opacity: disabled ? 0.4 : 1, cursor: disabled ? 'not-allowed' : 'pointer' }}>
              <div style={{ fontFamily: 'var(--font-thai-display)', fontSize: 22, fontWeight: 600 }}>{plan.months}</div>
              <div className="opt-desc" style={{ marginBottom: 8 }}>งวด</div>
              <div style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 16, color: 'var(--accent)' }}>
                ฿{fmt(monthly)}/เดือน
              </div>
              {disabled && <div style={{ fontSize: 10, color: 'var(--ink-3)', marginTop: 4 }}>ยอดต่ำกว่า ฿{fmt(plan.minAmount)}</div>}
            </button>
          );
        })}
      </div>
    </div>
  );
}

function ContactStep({ form, setField }) {
  return (
    <div>
      <p className="step-sub">เพื่อให้ทีมงานยืนยันและออกใบเสร็จ</p>
      <div className="field-row">
        <div className="field">
          <label>ชื่อ-นามสกุล</label>
          <input value={form.name} onChange={e => setField('name', e.target.value)} placeholder="เช่น คุณมาริ ดนตรี" />
        </div>
        <div className="field">
          <label>เบอร์โทร</label>
          <input value={form.phone} onChange={e => setField('phone', e.target.value)} placeholder="08x-xxx-xxxx" />
        </div>
      </div>
      <div className="field">
        <label>อีเมล (สำหรับรับใบเสร็จ)</label>
        <input value={form.email} onChange={e => setField('email', e.target.value)} placeholder="name@example.com" />
      </div>
    </div>
  );
}

// ── Main installment flow ──────────────────────────────────────────────────────

function InstallmentPage({ courses, onClose }) {
  const [step, setStep]       = React.useState(0);
  const [subjectId, setSub]   = React.useState('');
  const [pkgId, setPkg]       = React.useState('');
  const [planMonths, setPlan] = React.useState(null);
  const [form, setForm]       = React.useState({ name: '', phone: '', email: '' });
  const [loading, setLoading] = React.useState(false);
  const [error, setError]     = React.useState('');

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

  const course  = courses.find(c => c.id === subjectId);
  const pkg     = INSTALLMENT_PACKAGES.find(p => p.id === pkgId);
  const total   = course && pkg ? pkgPrice(course.price, pkg.sessions, pkg.discountPct) : 0;
  const monthly = planMonths ? monthlyAmt(total, planMonths) : 0;

  const steps = [
    {
      title: 'เลือกวิชา',
      content: <SubjectStep courses={courses} selected={subjectId} onSelect={setSub} />,
      canNext: !!subjectId,
    },
    {
      title: 'เลือกแพ็กเกจ',
      content: course ? <PackageStep pricePerSession={course.price} selected={pkgId} onSelect={setPkg} /> : null,
      canNext: !!pkgId,
    },
    {
      title: 'เลือกแผนผ่อน',
      content: <PlanStep totalAmount={total} selected={planMonths} onSelect={setPlan} />,
      canNext: !!planMonths,
    },
    {
      title: 'ข้อมูลติดต่อ',
      content: <ContactStep form={form} setField={setField} />,
      canNext: form.name.trim().length >= 2 && form.phone.trim().length >= 9 && form.email.includes('@'),
    },
  ];

  const submit = async () => {
    setLoading(true);
    setError('');
    try {
      const res = await fetch('/api/payment/create', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          subject:     subjectId,
          subjectName: course.name,
          sessions:    pkg.sessions,
          amount:      total,
          installments: planMonths,
          detail:      `เรียน${course.name} ${pkg.sessions} คาบ · ผ่อน ${planMonths} เดือน`,
          name:        form.name,
          phone:       form.phone,
          email:       form.email,
        }),
      });
      const data = await res.json();

      if (data.skipped) {
        setError('ระบบชำระเงินยังไม่พร้อม — กรุณาใส่ GB_PUBLIC_KEY และ GB_SECRET_KEY ใน .env');
        return;
      }
      if (!data.ok) {
        setError(data.error || 'เกิดข้อผิดพลาด กรุณาลองใหม่');
        return;
      }

      if (data.redirectUrl) {
        window.location.href = data.redirectUrl;
      } else if (data.html) {
        // GB Prime Pay returned an HTML auto-submit form
        const wrapper = document.createElement('div');
        wrapper.innerHTML = data.html;
        document.body.appendChild(wrapper);
        const gbForm = wrapper.querySelector('form');
        if (gbForm) gbForm.submit();
        else setError('ไม่สามารถเปิดหน้าชำระเงินได้ กรุณาติดต่อเจ้าหน้าที่');
      } else {
        setError('ไม่ได้รับ URL การชำระเงิน กรุณาลองใหม่');
      }
    } catch {
      setError('ไม่สามารถเชื่อมต่อเซิร์ฟเวอร์ได้');
    } finally {
      setLoading(false);
    }
  };

  const current = steps[step];

  return (
    <div className="container" style={{ paddingTop: 64, paddingBottom: 80 }}>
      <button className="btn btn-ghost btn-sm" style={{ marginBottom: 24 }} onClick={onClose}>← กลับ</button>

      {/* Header */}
      <div style={{ marginBottom: 32 }}>
        <div className="section-eyebrow">ซื้อแพ็กเกจ · INSTALLMENT</div>
        <h2 className="section-title">ผ่อนชำระ<br /><em>0% ดอกเบี้ย</em></h2>
        <p style={{ color: 'var(--ink-2)', marginTop: 8 }}>ชำระผ่านบัตรเครดิต ผ่าน GB Prime Pay — ปลอดภัยและได้รับการรับรอง</p>
      </div>

      <div className="booking-shell">
        {/* Progress bar */}
        <div className="booking-progress">
          {steps.map((s, i) => (
            <div key={i} className={`progress-step ${i === step ? 'active' : i < step ? 'done' : ''}`}></div>
          ))}
        </div>
        <div className="step-meta">ขั้นตอน {step + 1} จาก {steps.length}</div>

        <div className="booking-step">
          <h3>{current.title}</h3>
          {current.content}

          {error && (
            <div style={{ marginTop: 16, padding: '12px 16px', background: 'oklch(0.95 0.05 25)', border: '1px solid oklch(0.7 0.15 25)', borderRadius: 8, color: 'oklch(0.4 0.15 25)', fontSize: 14 }}>
              {error}
            </div>
          )}

          <div className="booking-actions" style={{ marginTop: 24 }}>
            {step > 0
              ? <button className="btn" onClick={() => setStep(step - 1)}>← ย้อนกลับ</button>
              : <span></span>
            }
            {step < steps.length - 1
              ? <button className="btn btn-primary" disabled={!current.canNext}
                  onClick={() => current.canNext && setStep(step + 1)}
                  style={{ opacity: current.canNext ? 1 : 0.5 }}>
                  ต่อไป →
                </button>
              : <button className="btn btn-accent" disabled={!current.canNext || loading}
                  onClick={() => current.canNext && submit()}
                  style={{ opacity: current.canNext ? 1 : 0.5 }}>
                  {loading ? 'กำลังส่งข้อมูล…' : 'ชำระผ่าน GB Prime Pay →'}
                </button>
            }
          </div>
        </div>

        {/* Summary (visible from step 2+) */}
        {step >= 1 && (
          <div style={{ marginTop: 28 }}>
            <div className="step-meta">สรุปการสั่งซื้อ</div>
            <div className="booking-summary">
              {course && <div className="summary-row"><span className="k">วิชา</span><span className="v">{course.name}</span></div>}
              {pkg    && <div className="summary-row"><span className="k">จำนวนคาบ</span><span className="v">{pkg.sessions} คาบ (ลด {pkg.discountPct}%)</span></div>}
              {total  > 0 && <div className="summary-row"><span className="k">ยอดรวม</span><span className="v" style={{ fontWeight: 700, color: 'var(--accent)' }}>฿{fmt(total)}</span></div>}
              {planMonths && <div className="summary-row"><span className="k">ผ่อน</span><span className="v">{planMonths} งวด · ฿{fmt(monthly)}/เดือน</span></div>}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

// ── Payment return page (after GB Prime Pay redirect) ─────────────────────────

function PaymentReturn({ onHome }) {
  const params  = new URLSearchParams(window.location.search);
  const code    = params.get('resultCode') || params.get('txnStatus') || '';
  const refNo   = params.get('referenceNo') || params.get('gbpReferenceNo') || '';
  const success = code === '00';

  return (
    <div className="container" style={{ paddingTop: 80, paddingBottom: 80, textAlign: 'center', maxWidth: 560, margin: '0 auto' }}>
      <div style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 72, color: success ? 'var(--accent)' : 'oklch(0.6 0.15 25)', lineHeight: 1 }}>
        {success ? '✓' : '✕'}
      </div>
      <h3 style={{ fontFamily: 'var(--font-thai-display)', fontSize: 32, margin: '16px 0 8px', fontWeight: 500 }}>
        {success ? 'ชำระเงินสำเร็จ' : 'การชำระเงินไม่สำเร็จ'}
      </h3>
      <p style={{ color: 'var(--ink-2)', marginBottom: 28 }}>
        {success
          ? 'ขอบคุณที่ไว้วางใจบ้านมาริ — ทีมงานจะติดต่อยืนยันนัดเวลาเรียนภายใน 24 ชม.'
          : 'เกิดข้อผิดพลาดในการชำระเงิน กรุณาลองใหม่หรือติดต่อเจ้าหน้าที่'}
      </p>
      {refNo && (
        <div style={{ background: 'var(--bg-2)', border: '1px solid var(--line-soft)', borderRadius: 10, padding: '12px 20px', marginBottom: 24, fontSize: 13, color: 'var(--ink-3)' }}>
          เลขอ้างอิง: <strong style={{ fontFamily: 'monospace', color: 'var(--ink)' }}>{refNo}</strong>
        </div>
      )}
      <div style={{ display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap' }}>
        <button className="btn btn-primary" onClick={onHome}>กลับสู่หน้าแรก</button>
        {!success && (
          <a href="https://line.me/R/ti/p/@baanmari" className="btn" target="_blank" rel="noopener noreferrer">
            ติดต่อทาง LINE
          </a>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { InstallmentPage, PaymentReturn });
