// Admin · Accounting Export — finance team dashboard with date/branch/
// doctor/staff filters, commission + DF calculations, and .xlsx export.
//
// Companion view: AdminRewardCreator — upgraded reward CMS with
// treatment-linked grants ("+1 session of Meso" for 5000 pts).

const { useState, useEffect } = React;

const ACC = {
  clover: '#1F4435', cloverDeep: '#122A20', cloverMid: '#2E5A47', cloverSoft: '#E6EEE8',
  gold: '#C9A66B', goldDeep: '#A8854A', goldSoft: '#F1E6CE',
  bone: '#F6F3EC', paper: '#FAF8F2',
  ink: '#14140F', ink2: '#2A2A24', mute: '#7A7A72',
  line: '#E6E2D7', line2: '#D5CFBE',
  pos: '#4F7A4A', neg: '#B5453A',
};

function AccBtn({ children, primary, onClick, style = {}, disabled }) {
  return (
    <button onClick={onClick} disabled={disabled} style={{
      padding: '8px 14px', borderRadius: 8, fontSize: 13, fontWeight: 600,
      border: primary ? 'none' : '1px solid ' + ACC.line2,
      background: primary ? ACC.clover : '#fff',
      color: primary ? '#fff' : ACC.ink,
      cursor: disabled ? 'default' : 'pointer',
      opacity: disabled ? 0.5 : 1,
      ...style,
    }}>{children}</button>
  );
}

// ─── Accounting export filters ───
function AccountingFilters({ filters, setFilters, role }) {
  const data = useData ? useData() : null;
  const branchList = (data && data.branches && data.branches.length) ? data.branches : BRANCHES;
  const { t } = useTranslation();
  return (
    <div style={{
      background: '#fff', border: '1px solid ' + ACC.line, borderRadius: 12,
      padding: 16, display: 'grid', gridTemplateColumns: 'repeat(5, 1fr) auto', gap: 12,
      alignItems: 'flex-end', marginBottom: 16,
    }}>
      <FilterField label={t('acc.date_range')}>
        <div style={{ display:'flex', alignItems:'center', gap: 6 }}>
          <FauxDate value="2026-05-01" />
          <span style={{ color: ACC.mute }}>→</span>
          <FauxDate value="2026-05-14" />
        </div>
      </FilterField>

      <FilterField label={t('acc.branch')}>
        <select value={filters.branch} onChange={e => setFilters({ ...filters, branch: e.target.value })}
          disabled={role === 'staff'}
          style={selectStyle}>
          <option value="">{t('acc.all_branches')}</option>
          {branchList.map(b => <option key={b.id} value={b.id}>{b.name}</option>)}
        </select>
      </FilterField>

      <FilterField label={t('acc.doctor')}>
        <select value={filters.doctor} onChange={e => setFilters({ ...filters, doctor: e.target.value })}
          style={selectStyle}>
          <option value="">{t('acc.all_doctors')}</option>
          {DOCTORS
            .filter(d => !filters.branch || d.branch === filters.branch)
            .filter(d => role !== 'staff' || d.branch === filters.branch || filters.branch === '')
            .map(d => <option key={d.id} value={d.id}>{d.name}</option>)}
        </select>
      </FilterField>

      <FilterField label={t('acc.staff')}>
        <select value={filters.staff} onChange={e => setFilters({ ...filters, staff: e.target.value })}
          style={selectStyle}>
          <option value="">{t('acc.all_staff')}</option>
          {STAFF
            .filter(s => !filters.branch || s.branch === filters.branch)
            .map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
        </select>
      </FilterField>

      <FilterField label={t('acc.treatment_category')}>
        <select value={filters.category} onChange={e => setFilters({ ...filters, category: e.target.value })} style={selectStyle}>
          <option value="">{t('acc.all_categories')}</option>
          <option value="injectable">Injectable</option>
          <option value="facial">Facial</option>
          <option value="laser">Laser</option>
          <option value="iv">IV / Drip</option>
        </select>
      </FilterField>

      <AccBtn onClick={() => setFilters({ branch: '', doctor: '', staff: '', category: '' })}>
        {t('acc.reset')}
      </AccBtn>
    </div>
  );
}
const selectStyle = {
  width: '100%', padding: '7px 10px', borderRadius: 8,
  border: '1px solid ' + ACC.line2, background: '#fff',
  fontFamily: 'inherit', fontSize: 13, color: ACC.ink,
  appearance: 'none', WebkitAppearance: 'none',
  backgroundImage: `url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%237A7A72' stroke-width='2'><path d='M6 9l6 6 6-6'/></svg>")`,
  backgroundRepeat: 'no-repeat', backgroundPosition: 'right 10px center', paddingRight: 26,
};
function FilterField({ label, children }) {
  return (
    <div>
      <div style={{ fontSize: 10.5, letterSpacing: 1.2, textTransform:'uppercase', color: ACC.mute, fontWeight: 600, marginBottom: 6 }}>
        {label}
      </div>
      {children}
    </div>
  );
}
function FauxDate({ value }) {
  return (
    <div style={{
      padding: '6px 10px', borderRadius: 8, border: '1px solid ' + ACC.line2,
      background: '#fff', fontSize: 13, color: ACC.ink, fontFamily: 'JetBrains Mono, monospace',
    }}>{value}</div>
  );
}

// ─── KPI tiles for the accounting view ───
function AccountingKPIs({ rows }) {
  const { t } = useTranslation();
  const sum = (k) => rows.reduce((s, r) => s + r[k], 0);
  const revenue = sum('revenue');
  const cogs = sum('cogs');
  const vat = sum('vat');
  const df = sum('df');
  const comm = sum('comm');
  const net = revenue - cogs - vat - df - comm;
  const tiles = [
    { label: t('acc.gross_revenue'), value: fmtTHB(revenue), tone: 'pos' },
    { label: t('acc.doctor_fee'),    value: fmtTHB(df),      tone: 'neutral', sub: '∑ DF%' },
    { label: t('acc.staff_comm'),    value: fmtTHB(comm),    tone: 'neutral', sub: '∑ COMM%' },
    { label: t('acc.net_after'),     value: fmtTHB(net),     tone: 'pos', emphasize: true },
  ];
  return (
    <div style={{ display:'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12, marginBottom: 14 }}>
      {tiles.map((tile, i) => (
        <div key={i} style={{
          background: tile.emphasize ? ACC.clover : '#fff',
          color: tile.emphasize ? '#fff' : ACC.ink,
          border: '1px solid ' + (tile.emphasize ? ACC.clover : ACC.line),
          borderRadius: 12, padding: '16px 18px',
        }}>
          <div style={{
            fontSize: 11, letterSpacing: 1.4, textTransform:'uppercase',
            color: tile.emphasize ? 'rgba(255,255,255,0.6)' : ACC.mute, fontWeight: 600,
          }}>{tile.label}</div>
          <div className="serif" style={{ fontSize: 28, marginTop: 8, letterSpacing: -0.5,
            color: tile.emphasize ? ACC.gold : ACC.ink }}>{tile.value}</div>
          {tile.sub && (
            <div style={{ fontSize: 11, marginTop: 4, color: tile.emphasize ? 'rgba(255,255,255,0.6)' : ACC.mute, fontFamily: 'JetBrains Mono, monospace' }}>
              {tile.sub}
            </div>
          )}
        </div>
      ))}
    </div>
  );
}

// ─── Accounting transactions table ───
function AccountingTable({ rows }) {
  const { t } = useTranslation();
  return (
    <div style={{ background:'#fff', border:'1px solid '+ACC.line, borderRadius: 12, overflow:'hidden' }}>
      <div style={{
        padding: '14px 18px', borderBottom: '1px solid ' + ACC.line,
        display:'flex', justifyContent:'space-between', alignItems:'center',
      }}>
        <div className="serif" style={{ fontSize: 17, color: ACC.ink }}>
          {t('acc.transactions')} <span style={{ color: ACC.mute, fontSize: 13, fontFamily: 'DM Sans, sans-serif' }}>· {rows.length} rows</span>
        </div>
        <div style={{ fontSize: 11.5, color: ACC.mute, fontFamily: 'JetBrains Mono, monospace' }}>
          DF% &amp; COMM% applied per doctor / staff profile
        </div>
      </div>

      <div style={{
        display:'grid', gridTemplateColumns: '130px 100px 130px 150px 150px 1.2fr 110px 90px 90px 110px',
        padding: '10px 18px', background: ACC.bone,
        fontSize: 10.5, letterSpacing: 1.2, textTransform:'uppercase', color: ACC.mute, fontWeight: 600,
      }}>
        <div>{t('acc.txn_id')}</div>
        <div>{t('acc.date')}</div>
        <div>{t('acc.branch')}</div>
        <div>{t('acc.doctor')}</div>
        <div>{t('acc.staff')}</div>
        <div>{t('acc.treatment')}</div>
        <div style={{ textAlign:'right' }}>{t('acc.revenue')}</div>
        <div style={{ textAlign:'right' }}>DF</div>
        <div style={{ textAlign:'right' }}>COMM</div>
        <div style={{ textAlign:'right' }}>{t('acc.gross')}</div>
      </div>

      {rows.map((r, i) => (
        <div key={r.id} style={{
          display:'grid', gridTemplateColumns: '130px 100px 130px 150px 150px 1.2fr 110px 90px 90px 110px',
          padding: '12px 18px', alignItems:'center', fontSize: 12.5,
          borderTop: '1px solid ' + ACC.line,
        }}>
          <div className="mono" style={{ color: ACC.mute, fontSize: 11 }}>{r.id}</div>
          <div className="mono" style={{ color: ACC.ink2 }}>{r.date}</div>
          <div style={{ color: ACC.ink2 }}>{branchName(r.branch)}</div>
          <div style={{ color: ACC.ink }}>
            <div style={{ fontWeight: 600 }}>{r.doctor.name}</div>
            <div style={{ fontSize: 10.5, color: ACC.mute }}>DF {r.doctor.df}%</div>
          </div>
          <div style={{ color: ACC.ink }}>
            <div>{r.staff.name}</div>
            <div style={{ fontSize: 10.5, color: ACC.mute }}>COMM {r.staff.commission}%</div>
          </div>
          <div style={{ color: ACC.ink }}>{r.treatment}</div>
          <div className="mono" style={{ textAlign:'right', color: ACC.ink, fontWeight: 600 }}>{fmtTHB(r.revenue)}</div>
          <div className="mono" style={{ textAlign:'right', color: ACC.goldDeep }}>−{fmtTHB(r.df).replace('฿','')}</div>
          <div className="mono" style={{ textAlign:'right', color: ACC.goldDeep }}>−{fmtTHB(r.comm).replace('฿','')}</div>
          <div className="mono" style={{ textAlign:'right', color: ACC.clover, fontWeight: 700 }}>{fmtTHB(r.gross)}</div>
        </div>
      ))}
    </div>
  );
}

// ─── Main Accounting view ───
function AccountingView({ role = 'admin', forcedBranch = null }) {
  const { t } = useTranslation();
  const [filters, setFilters] = useState({
    branch: role === 'staff' ? (forcedBranch || 'thonglor') : '',
    doctor: '', staff: '', category: '',
  });
  const [exporting, setExporting] = useState(false);
  const [exported, setExported] = useState(false);

  const filtered = TRANSACTIONS
    .filter(tx => !filters.branch || tx.branch === filters.branch)
    .filter(tx => !filters.doctor || tx.doctorId === filters.doctor)
    .filter(tx => !filters.staff || tx.staffId === filters.staff)
    .map(computeRow);

  // CSV-safe quoting: wrap in quotes, escape inner quotes by doubling.
  const csvCell = (v) => {
    const s = v == null ? '' : String(v);
    return /[",\n\r]/.test(s) ? '"' + s.replace(/"/g, '""') + '"' : s;
  };

  const triggerDownload = (filename, blob) => {
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    setTimeout(() => URL.revokeObjectURL(url), 1000);
  };

  const buildCSV = () => {
    const headers = ['Date','Invoice','Branch','Doctor','Staff','Customer','Treatment',
                     'Revenue','COGS','VAT','Doctor Fee','Staff Comm','Gross'];
    const lines = [headers.map(csvCell).join(',')];
    filtered.forEach(r => {
      lines.push([
        r.date,
        r.id,
        branchName(r.branch),
        r.doctor?.name || r.doctorId,
        r.staff?.name  || r.staffId,
        r.customer,
        r.treatment,
        r.revenue, r.cogs, r.vat, r.df, r.comm, r.gross,
      ].map(csvCell).join(','));
    });
    // Prepend UTF-8 BOM so Excel renders Thai characters correctly.
    return '﻿' + lines.join('\r\n');
  };

  const runExport = () => {
    if (filtered.length === 0) {
      alert('ไม่มีข้อมูลที่จะ Export');
      return;
    }
    setExporting(true);
    try {
      const stamp    = new Date().toISOString().slice(0, 10);
      const filename = `clover-accounting-${stamp}.csv`;
      const blob     = new Blob([buildCSV()], { type: 'text/csv;charset=utf-8;' });
      triggerDownload(filename, blob);
      setExported(true);
      setTimeout(() => setExported(false), 2400);

      // Activity log: data export
      if (typeof logActivity === 'function') {
        logActivity({
          action_type: 'export_accounting',
          action_label: `Exported accounting report (${filtered.length} rows)`,
          branch_id: forcedBranch || null,
          details: { rows: filtered.length, filename },
        });
      }
    } catch (err) {
      alert('Export failed: ' + err.message);
    } finally {
      setExporting(false);
    }
  };

  return (
    <div>
      <AdminTopbar
        title={t('acc.title')}
        subtitle={t('acc.subtitle')}
        right={<>
          <AccBtn onClick={runExport} disabled={exporting}>
            <IconDownload size={14} style={{verticalAlign:-2, marginRight:6}}/>{t('acc.csv')}
          </AccBtn>
          <AccBtn primary onClick={runExport} disabled={exporting}>
            {exporting
              ? <><span className="mono" style={{ marginRight: 6 }}>•••</span>{t('acc.exporting')}</>
              : <><IconDownload size={14} style={{verticalAlign:-2, marginRight:6}}/>{t('acc.export_xlsx')}</>}
          </AccBtn>
        </>}
      />

      <div style={{ padding: '20px 28px 28px' }}>
        {role === 'staff' && (
          <div style={{
            padding: '10px 14px', background: ACC.cloverSoft, border: '1px solid ' + ACC.cloverMid,
            borderRadius: 10, fontSize: 12.5, color: ACC.clover, marginBottom: 14,
            display:'flex', alignItems:'center', gap: 10,
          }}>
            <div style={{ width: 6, height: 6, borderRadius: 3, background: ACC.clover }}/>
            {t('acc.rbac_scope', { branch: branchName(forcedBranch || 'thonglor') })}
          </div>
        )}

        <AccountingFilters filters={filters} setFilters={setFilters} role={role} />
        <AccountingKPIs rows={filtered} />
        <AccountingTable rows={filtered} />

        {/* Toast */}
        {exported && (
          <div className="slide-up" style={{
            position: 'fixed', top: 86, right: 36, zIndex: 100,
            background: ACC.clover, color: '#fff', padding: '12px 18px', borderRadius: 10,
            boxShadow: '0 12px 30px rgba(31,68,53,0.3)',
            display:'flex', alignItems:'center', gap: 10, fontSize: 13.5,
          }}>
            <IconCheck size={16} color="#fff"/>
            {t('acc.export_done', { rows: filtered.length })}
          </div>
        )}
      </div>
    </div>
  );
}

// ──────────────────────────────────────────────────────────────
// Reward creator with treatment-linked grants
// ──────────────────────────────────────────────────────────────
function AdminRewardCreator() {
  const { t } = useTranslation();
  const [grantKind, setGrantKind] = useState('session');
  const [template, setTemplate] = useState('meso-glow');
  const [qty, setQty] = useState(1);
  const [cost, setCost] = useState(5000);
  const [titleEN, setTitleEN] = useState('Meso Glow · +1 session bonus');
  const [titleTH, setTitleTH] = useState('Meso Glow · เพิ่ม 1 เซสชัน');
  const [descEN, setDescEN] = useState('Adds one Meso Glow session to your active course balance immediately upon redemption.');
  const [descTH, setDescTH] = useState('เพิ่ม 1 เซสชันของ Meso Glow เข้าสู่คอร์สที่ใช้งานอยู่ของคุณทันทีหลังแลก');

  const templates = [
    { id: 'meso-glow',      name: 'Meso Glow',            category: 'Injectable', unit: 'session' },
    { id: 'hydrafacial-md', name: 'Hydrafacial MD',       category: 'Facial',     unit: 'session' },
    { id: 'pico-toning',    name: 'Pico Laser Toning',    category: 'Laser',      unit: 'session' },
    { id: 'glow-iv',        name: 'Glow IV Drip',         category: 'IV',         unit: 'session' },
    { id: 'botulinum',      name: 'Botulinum Reserve',    category: 'Injectable', unit: 'units' },
    { id: 'filler-volift',  name: 'Filler · Juvéderm Volift', category: 'Injectable', unit: 'cc' },
  ];
  const tmpl = templates.find(x => x.id === template);

  return (
    <div>
      <AdminTopbar
        title={t('reward.title')}
        subtitle={t('reward.subtitle')}
        right={<><AccBtn>{t('common.discard')}</AccBtn><AccBtn primary>{t('common.publish')}</AccBtn></>}
      />

      <div style={{ padding: 28, display:'grid', gridTemplateColumns: '1.4fr 1fr', gap: 18 }}>
        {/* Form */}
        <div style={{ background:'#fff', border:'1px solid '+ACC.line, borderRadius: 14, padding: 22 }}>

          {/* Step 1 — Grant type */}
          <Step n={1} title={t('reward.step_grant')}>
            <div style={{ display:'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8 }}>
              {[
                { id: 'session', label: t('reward.kind_session'), I: IconLayers, desc: t('reward.kind_session_desc') },
                { id: 'voucher', label: t('reward.kind_voucher'), I: IconReceipt, desc: t('reward.kind_voucher_desc') },
                { id: 'physical', label: t('reward.kind_physical'), I: IconGift, desc: t('reward.kind_physical_desc') },
                { id: 'upgrade',  label: t('reward.kind_upgrade'),  I: IconStar, desc: t('reward.kind_upgrade_desc') },
              ].map(k => {
                const on = grantKind === k.id;
                return (
                  <div key={k.id} onClick={() => setGrantKind(k.id)} style={{
                    padding: 14, borderRadius: 10, cursor:'pointer',
                    background: on ? ACC.cloverSoft : '#fff',
                    border: '1.5px solid ' + (on ? ACC.clover : ACC.line),
                  }}>
                    <k.I size={18} color={on ? ACC.clover : ACC.mute}/>
                    <div style={{ fontSize: 12.5, fontWeight: 600, color: on ? ACC.clover : ACC.ink, marginTop: 8 }}>{k.label}</div>
                    <div style={{ fontSize: 10.5, color: ACC.mute, marginTop: 3, lineHeight: 1.4 }}>{k.desc}</div>
                  </div>
                );
              })}
            </div>
          </Step>

          {/* Step 2 — Linked treatment (only when grant kind is session) */}
          {grantKind === 'session' && (
            <Step n={2} title={t('reward.step_link')}>
              <div style={{ display:'grid', gridTemplateColumns: '1.4fr 1fr', gap: 12 }}>
                <div>
                  <FieldLabelInline label={t('reward.treatment_template')} />
                  <select value={template} onChange={e => setTemplate(e.target.value)} style={selectStyle}>
                    {templates.map(tt => <option key={tt.id} value={tt.id}>{tt.name} — {tt.category}</option>)}
                  </select>
                </div>
                <div>
                  <FieldLabelInline label={tmpl.unit === 'session' ? t('reward.qty_sessions') : t('reward.qty_' + tmpl.unit)} />
                  <div style={{ display:'flex', alignItems:'center', gap: 8, border: '1px solid ' + ACC.line2, borderRadius: 8, padding: '4px 8px', background:'#fff' }}>
                    <button onClick={() => setQty(Math.max(1, qty - (tmpl.unit === 'cc' ? 0.5 : 1)))} style={qtyBtn}>−</button>
                    <input type="number" value={qty} onChange={e => setQty(parseFloat(e.target.value) || 0)}
                      style={{ flex: 1, border:'none', outline:'none', textAlign:'center', fontSize: 16, fontWeight: 600, fontFamily: 'inherit', background:'transparent', color: ACC.clover }}/>
                    <button onClick={() => setQty(qty + (tmpl.unit === 'cc' ? 0.5 : 1))} style={qtyBtn}>+</button>
                  </div>
                </div>
              </div>

              <div style={{ marginTop: 12, padding: 12, background: ACC.bone, borderRadius: 8, fontSize: 12, color: ACC.ink2, lineHeight: 1.6 }}>
                <strong style={{ color: ACC.clover }}>{t('reward.rule_preview')}:</strong>{' '}
                {t('reward.rule_preview_text', { qty, unit: tmpl.unit, name: tmpl.name })}
                <div className="mono" style={{ marginTop: 8, padding: '6px 10px', background:'#fff', border: '1px solid ' + ACC.line, borderRadius: 6, fontSize: 11, color: ACC.clover }}>
                  {`INSERT INTO course_balances (customer_id, template_id, quota_total, source)`}<br/>
                  {`VALUES ($cid, '${template}', ${qty}, 'reward:${cost}pts');`}
                </div>
              </div>
            </Step>
          )}

          {grantKind === 'voucher' && (
            <Step n={2} title={t('reward.step_voucher')}>
              <div style={{ display:'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                <div>
                  <FieldLabelInline label={t('reward.discount_amount')} />
                  <FauxField mono>฿2,400</FauxField>
                </div>
                <div>
                  <FieldLabelInline label={t('reward.valid_for')} />
                  <FauxField>90 days from redemption</FauxField>
                </div>
              </div>
            </Step>
          )}

          {grantKind === 'physical' && (
            <Step n={2} title={t('reward.step_physical')}>
              <div style={{ display:'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                <div>
                  <FieldLabelInline label={t('reward.sku')} />
                  <FauxField mono>LAMER-30</FauxField>
                </div>
                <div>
                  <FieldLabelInline label={t('reward.inventory')} />
                  <FauxField>42 units across 8 branches</FauxField>
                </div>
              </div>
            </Step>
          )}

          {grantKind === 'upgrade' && (
            <Step n={2} title={t('reward.step_upgrade')}>
              <div>
                <FieldLabelInline label={t('reward.upgrade_target')} />
                <FauxField>Glow IV → Premium Glow IV (+vitamin pack)</FauxField>
              </div>
            </Step>
          )}

          {/* Step 3 — Bilingual copy */}
          <Step n={3} title={t('reward.step_copy')}>
            <BilingualPair
              labelEN="Title · English" labelTH="ชื่อ · ภาษาไทย" schemaKey="title"
              valueEN={titleEN} setEN={setTitleEN} valueTH={titleTH} setTH={setTitleTH}
            />
            <div style={{ height: 14 }}/>
            <BilingualPair
              labelEN="Description · English" labelTH="คำอธิบาย · ภาษาไทย" schemaKey="desc"
              valueEN={descEN} setEN={setDescEN} valueTH={descTH} setTH={setDescTH}
              multi
            />
          </Step>

          {/* Step 4 — Cost + audience */}
          <Step n={4} title={t('reward.step_publish')} last>
            <div style={{ display:'grid', gridTemplateColumns: '1fr 1.4fr', gap: 12 }}>
              <div>
                <FieldLabelInline label={t('reward.point_cost')}/>
                <div style={{
                  border: '1px solid ' + ACC.line2, borderRadius: 8, padding: '8px 12px',
                  display:'flex', alignItems:'center', gap: 6, background: '#fff',
                }}>
                  <input type="number" value={cost} onChange={(e) => setCost(parseInt(e.target.value) || 0)}
                    style={{ flex: 1, border:'none', outline:'none', fontSize: 22, fontWeight: 600, fontFamily: 'JetBrains Mono, monospace', color: ACC.clover, background:'transparent' }}/>
                  <span style={{ fontSize: 11, color: ACC.mute, letterSpacing: 1 }}>PTS</span>
                </div>
                <div style={{ fontSize: 11, color: ACC.mute, marginTop: 4 }}>
                  ≈ {fmtTHB(cost * 25)} {t('reward.spend_equivalent')}
                </div>
              </div>
              <div>
                <FieldLabelInline label={t('admin.audience')}/>
                <div style={{ display:'flex', gap: 6, flexWrap:'wrap' }}>
                  {['Diamond','Platinum','Gold','Silver'].map((a, i) => (
                    <div key={a} style={{
                      padding: '6px 12px', borderRadius: 999,
                      background: i < 3 ? ACC.cloverSoft : '#fff',
                      border: '1px solid ' + (i < 3 ? ACC.clover : ACC.line2),
                      color: i < 3 ? ACC.clover : ACC.ink2,
                      fontSize: 12, fontWeight: 600, cursor: 'pointer',
                    }}>{a}</div>
                  ))}
                </div>
              </div>
            </div>
          </Step>
        </div>

        {/* Live preview */}
        <RewardPreview
          titleEN={titleEN} titleTH={titleTH}
          descEN={descEN} descTH={descTH}
          cost={cost} grantKind={grantKind}
          tmpl={tmpl} qty={qty}
        />
      </div>
    </div>
  );
}

const qtyBtn = {
  width: 28, height: 28, borderRadius: 6, border:'1px solid ' + ACC.line2,
  background:'#fff', cursor:'pointer', fontSize: 16, color: ACC.clover, fontWeight: 600,
};

function Step({ n, title, children, last }) {
  return (
    <div style={{ paddingBottom: last ? 0 : 22, marginBottom: last ? 0 : 22, borderBottom: last ? 'none' : '1px solid ' + ACC.line }}>
      <div style={{ display:'flex', alignItems:'center', gap: 10, marginBottom: 14 }}>
        <div style={{
          width: 24, height: 24, borderRadius: 12, background: ACC.clover, color: '#fff',
          fontSize: 12, fontWeight: 700, display:'flex', alignItems:'center', justifyContent:'center',
        }}>{n}</div>
        <div className="serif" style={{ fontSize: 18, color: ACC.clover, letterSpacing: -0.2 }}>{title}</div>
      </div>
      {children}
    </div>
  );
}

function FieldLabelInline({ label }) {
  return <div style={{ fontSize: 11, letterSpacing: 1.2, textTransform:'uppercase', color: ACC.mute, fontWeight: 600, marginBottom: 6 }}>{label}</div>;
}
function FauxField({ children, mono }) {
  return (
    <div style={{
      border:'1px solid ' + ACC.line2, borderRadius: 8, padding: '10px 12px', background:'#fff',
      fontSize: 13, color: ACC.ink, fontFamily: mono ? 'JetBrains Mono, monospace' : 'inherit',
    }}>{children}</div>
  );
}
function BilingualPair({ labelEN, labelTH, valueEN, setEN, valueTH, setTH, multi, schemaKey }) {
  const Input = multi ? 'textarea' : 'input';
  return (
    <div>
      <div style={{ display:'flex', alignItems:'baseline', gap: 8, marginBottom: 6 }}>
        <span style={{ fontSize: 11, fontWeight: 600, color: ACC.ink }}>{labelEN.split(' · ')[0]}</span>
        <span style={{ fontSize: 11, color: ACC.mute }}>·</span>
        <span style={{ fontSize: 11, fontWeight: 600, color: ACC.ink }}>{labelTH.split(' · ')[0]}</span>
        {schemaKey && <span className="mono" style={{ fontSize: 10, color: ACC.mute, marginLeft: 'auto' }}>{schemaKey}_th · {schemaKey}_en</span>}
      </div>
      <div style={{ display:'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
        <FlagInput flag="EN">
          <Input value={valueEN} onChange={(e) => setEN(e.target.value)} rows={multi ? 3 : undefined} style={fieldInput}/>
        </FlagInput>
        <FlagInput flag="TH">
          <Input value={valueTH} onChange={(e) => setTH(e.target.value)} rows={multi ? 3 : undefined} lang="th" style={fieldInput}/>
        </FlagInput>
      </div>
    </div>
  );
}
const fieldInput = {
  width: '100%', border:'none', outline:'none',
  fontFamily: 'DM Sans, "IBM Plex Sans Thai", sans-serif',
  fontSize: 13.5, color: ACC.ink, background:'transparent', padding:'4px 0', resize:'none',
};
function FlagInput({ flag, children }) {
  return (
    <div style={{
      border:'1px solid '+ACC.line2, borderRadius: 8, padding:'8px 12px', background:'#fff',
      display:'flex', flexDirection:'column', gap: 4,
    }}>
      <span style={{ fontSize: 9.5, letterSpacing: 0.8, color: ACC.mute, fontWeight: 700, textTransform:'uppercase' }}>{flag}</span>
      {children}
    </div>
  );
}

// ─── Reward preview card ───
function RewardPreview({ titleEN, titleTH, descEN, descTH, cost, grantKind, tmpl, qty }) {
  const { t } = useTranslation();
  const [previewLang, setPreviewLang] = useState('en');
  const title = previewLang === 'en' ? titleEN : titleTH;
  const desc = previewLang === 'en' ? descEN : descTH;

  const grantSummary = () => {
    if (grantKind === 'session') return `+${qty} ${tmpl.unit === 'session' ? 'session' : tmpl.unit} · ${tmpl.name}`;
    if (grantKind === 'voucher') return '฿2,400 voucher · 90 days';
    if (grantKind === 'physical') return 'Physical product · ship to branch';
    return 'Service upgrade';
  };

  return (
    <div>
      <div style={{ display:'flex', alignItems:'center', gap: 10, marginBottom: 10 }}>
        <div style={{ fontSize: 11, letterSpacing: 1.4, textTransform:'uppercase', color: ACC.mute, fontWeight: 600 }}>
          {t('reward.live_preview')}
        </div>
        <div style={{ flex: 1 }}/>
        <SegmentedLang lang={previewLang} setLang={setPreviewLang} compact />
      </div>

      {/* Customer-facing reward card */}
      <div style={{
        background: '#fff', border:'1px solid '+ACC.line, borderRadius: 16, padding: 16,
        boxShadow: '0 12px 30px rgba(31,68,53,0.1)',
      }}>
        <div className="stripes" style={{ height: 80, borderRadius: 10, fontSize: 9 }}>IMG</div>
        <div style={{ marginTop: 14 }}>
          <span style={{
            display:'inline-block', fontSize: 10, padding:'3px 8px', borderRadius: 4,
            background: ACC.cloverSoft, color: ACC.clover, fontWeight: 700, letterSpacing: 0.5,
          }}>
            {grantKind === 'session' ? 'TREATMENT GRANT' : grantKind.toUpperCase()}
          </span>
          <div className="serif" lang={previewLang} style={{ fontSize: 20, marginTop: 8, color: ACC.ink, lineHeight: 1.2 }}>
            {title}
          </div>
          <div lang={previewLang} style={{ fontSize: 12.5, color: ACC.mute, marginTop: 6, lineHeight: 1.55 }}>
            {desc}
          </div>
        </div>

        {grantKind === 'session' && (
          <div style={{
            marginTop: 14, padding: '10px 12px', background: ACC.cloverSoft, borderRadius: 8,
            fontSize: 12, color: ACC.clover, fontWeight: 600, display:'flex', alignItems:'center', gap: 8,
          }}>
            <IconLayers size={14} color={ACC.clover}/>
            {grantSummary()}
          </div>
        )}

        <div style={{
          marginTop: 14, paddingTop: 14, borderTop: '1px solid ' + ACC.line,
          display:'flex', justifyContent:'space-between', alignItems:'center',
        }}>
          <div className="mono" style={{ fontSize: 11, color: ACC.mute }}>
            {previewLang === 'en' ? `${cost.toLocaleString()} pts to redeem` : `${cost.toLocaleString()} คะแนน`}
          </div>
          <div style={{
            padding:'7px 14px', borderRadius: 8, background: ACC.clover, color:'#fff',
            fontSize: 12, fontWeight: 600,
          }}>
            {previewLang === 'en' ? 'Redeem' : 'แลกเลย'}
          </div>
        </div>
      </div>

      {/* JSON schema preview */}
      <div style={{ marginTop: 14, background: ACC.cloverDeep, color: '#E6EEE8', borderRadius: 10, padding: 14, fontFamily: 'JetBrains Mono, monospace', fontSize: 10.5, lineHeight: 1.55, overflow:'auto' }}>
        <div style={{ color: ACC.gold, marginBottom: 6 }}>// rewards row</div>
        <pre style={{ margin: 0, whiteSpace:'pre' }}>
{`{
  id          : "rw_meso_bonus_1",
  title_en    : "${truncStr(titleEN, 32)}",
  title_th    : "${truncStr(titleTH, 22)}",
  desc_en     : "${truncStr(descEN, 30)}",
  desc_th     : "${truncStr(descTH, 18)}",
  cost_pts    : ${cost},
  grant_kind  : "${grantKind}",${grantKind === 'session' ? `
  grant_template : "${tmpl.id}",
  grant_qty      : ${qty},` : ''}
  audience    : ["diamond","platinum","gold"],
  status      : "draft"
}`}
        </pre>
      </div>
    </div>
  );
}

function truncStr(s, n) { s = String(s || ''); return s.length > n ? s.slice(0, n - 1) + '…' : s; }

Object.assign(window, { AccountingView, AdminRewardCreator });
