/* ============ Personal income tax (บุคคลธรรมดา) ============ */
function PersonalPage({ role, toast }) {
  const inc = D.personalIncome.reduce((a, d) => a + d.amount, 0);
  const ded = D.personalExp.reduce((a, d) => a + d.amount, 0);
  const net = inc - ded;
  const tax = window.estTax(net);
  const maxInc = Math.max(...D.personalIncome.map((d) => d.amount));

  return (
    <>
      <div className="page-head">
        <div><div className="pt">ภาษีบุคคลธรรมดา</div><div className="ps">{D.personal.name} · ปีภาษี 2568 · เตรียมข้อมูล ภ.ง.ด.90/91</div></div>
        <div className="spacer"></div>
        <button className="btn btn-primary" onClick={() => toast('กำลังสร้างรายงานสรุปภาษีบุคคล…')}><Icon name="download" className="ic" />ส่งออกให้นักบัญชี</button>
      </div>

      <div className="grid" style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', marginBottom: 16 }}>
        <Stat label="รายได้รวมทั้งปี" icon="income" value={D.baht(inc, 0)} />
        <Stat label="ค่าใช้จ่าย + ลดหย่อน" icon="expense" iconBg="var(--info-bg)" iconColor="var(--info)" value={D.baht(ded, 0)} />
        <Stat label="เงินได้สุทธิ" icon="pie" iconBg="var(--ok-bg)" iconColor="var(--ok)" value={D.baht(net, 0)} sub="ฐานคำนวณภาษี" />
        <Stat label="ภาษีโดยประมาณ" icon="vat" iconBg="var(--warn-bg)" iconColor="var(--warn)" value={D.baht(tax, 0)} sub={'effective ' + (tax / inc * 100).toFixed(1) + '%'} />
      </div>

      <div className="grid" style={{ gridTemplateColumns: 'minmax(0, 1fr) minmax(0, 1fr)', alignItems: 'start', marginBottom: 16 }}>
        <div className="card">
          <div className="card-head"><h3>รายได้แยกประเภท</h3><span className="badge muted" style={{ marginLeft: 'auto' }}>มาตรา 40</span></div>
          <div className="card-pad" style={{ display: 'flex', flexDirection: 'column', gap: 13 }}>
            {D.personalIncome.map((d) => (
              <div key={d.id}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 5, fontSize: 13.5 }}><span style={{ fontWeight: 500 }}>{d.label}</span><span className="num" style={{ fontWeight: 600 }}>{D.baht(d.amount, 0)}</span></div>
                <div className="bar-track"><div className="bar-fill" style={{ width: (d.amount / maxInc * 100) + '%' }}></div></div>
              </div>
            ))}
          </div>
        </div>

        <div className="card">
          <div className="card-head"><h3>ค่าใช้จ่าย &amp; ค่าลดหย่อน</h3></div>
          <div className="card-pad" style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
            {D.personalExp.map((d) => (
              <div key={d.id} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '10px 0', borderBottom: '1px solid var(--line-2)', fontSize: 13.5 }}>
                <span style={{ display: 'flex', alignItems: 'center', gap: 9 }}><span className="badge muted" style={{ fontSize: 10 }}>{d.type === 'standard' ? 'ค่าใช้จ่าย' : 'ลดหย่อน'}</span>{d.label}</span>
                <span className="num" style={{ fontWeight: 600 }}>{D.baht(d.amount, 0)}</span>
              </div>
            ))}
            <button className="btn btn-soft btn-sm" style={{ marginTop: 12, alignSelf: 'flex-start' }}><Icon name="plus" className="ic" />เพิ่มค่าลดหย่อน</button>
          </div>
        </div>
      </div>

      {/* tax bracket breakdown */}
      <div className="card">
        <div className="card-head"><h3>คำนวณภาษีแบบขั้นบันได</h3><div className="sub">อัตราก้าวหน้า · เงินได้สุทธิ {D.baht(net, 0)}</div></div>
        <div className="tbl-wrap">
          <table className="tbl">
            <thead><tr><th>ขั้นเงินได้สุทธิ</th><th className="c">อัตรา</th><th className="r">เงินได้ในขั้น</th><th className="r">ภาษีในขั้น</th></tr></thead>
            <tbody>
              {taxBrackets(net).map((b, i) => (
                <tr key={i} style={{ opacity: b.amount > 0 ? 1 : 0.4 }}>
                  <td>{b.label}</td>
                  <td className="c"><span className={'badge ' + (b.rate === 0 ? 'muted' : b.rate >= 0.2 ? 'danger' : 'warn')}>{(b.rate * 100)}%</span></td>
                  <td className="r num">{b.amount > 0 ? D.fmt0(b.amount) : '—'}</td>
                  <td className="r num" style={{ fontWeight: 600 }}>{b.tax > 0 ? D.fmt0(b.tax) : '—'}</td>
                </tr>
              ))}
            </tbody>
            <tfoot><tr style={{ background: 'var(--surface-2)', fontWeight: 700 }}><td colSpan="3" style={{ padding: 12 }}>ภาษีที่ต้องชำระโดยประมาณ</td><td className="r num" style={{ padding: 12, fontSize: 15, color: 'var(--warn)' }}>{D.baht(tax, 0)}</td></tr></tfoot>
          </table>
        </div>
      </div>
      <div className="callout warn" style={{ marginTop: 16 }}><Icon name="info" className="ic" /><div>ตัวเลขนี้เป็นการ<b>ประมาณการเบื้องต้น</b> ยังไม่รวมค่าลดหย่อนส่วนตัว/คู่สมรส/บุตร และเครดิตภาษีอื่น โปรดตรวจสอบกับสำนักงานบัญชีก่อนยื่นจริง</div></div>
    </>
  );
}
function taxBrackets(net) {
  const defs = [[0, 150000, 0], [150000, 300000, .05], [300000, 500000, .1], [500000, 750000, .15], [750000, 1000000, .2], [1000000, 2000000, .25], [2000000, 5000000, .3], [5000000, Infinity, .35]];
  return defs.map(([lo, hi, rate]) => {
    const amount = Math.max(0, Math.min(net, hi) - lo);
    return { label: hi === Infinity ? '5,000,001 บาทขึ้นไป' : `${D.fmt0(lo + (lo > 0 ? 1 : 0))} – ${D.fmt0(hi)}`, rate, amount, tax: amount * rate };
  });
}

/* ============ Export package for accountant ============ */
function ExportPage({ toast }) {
  const [building, setBuilding] = useState(false);
  const [done, setDone] = useState(false);
  const [opts, setOpts] = useState({ buyTax: true, sellTax: true, pp30: true, pl: true, zip: true, markSent: true });
  const items = [
    { k: 'buyTax', label: 'รายงานภาษีซื้อ (Excel)', icon: 'fileText', size: '48 KB', file: 'ภาษีซื้อ_พค68.xlsx' },
    { k: 'sellTax', label: 'รายงานภาษีขาย (Excel)', icon: 'fileText', size: '32 KB', file: 'ภาษีขาย_พค68.xlsx' },
    { k: 'pp30', label: 'สรุป ภ.พ.30 (PDF)', icon: 'file', size: '120 KB', file: 'ภพ30_พค68.pdf' },
    { k: 'pl', label: 'สรุปรายรับ-รายจ่าย (PDF)', icon: 'file', size: '96 KB', file: 'รายรับรายจ่าย_พค68.pdf' },
    { k: 'zip', label: 'ไฟล์ใบเสร็จ/ใบกำกับทั้งหมด (ZIP)', icon: 'folder', size: '14.2 MB', file: 'เอกสารต้นฉบับ_พค68.zip' },
  ];

  const build = () => {
    setBuilding(true); setDone(false);
    setTimeout(() => { setBuilding(false); setDone(true); toast('เตรียมแพ็กส่งบัญชีเรียบร้อย'); }, 1900);
  };

  return (
    <>
      <div className="page-head">
        <div><div className="pt">แพ็กส่งสำนักงานบัญชี</div><div className="ps">รวบรวมรายงานและเอกสารทั้งหมดของเดือน ส่งให้สำนักงานบัญชีในคลิกเดียว</div></div>
      </div>

      <div className="grid" style={{ gridTemplateColumns: 'minmax(0, 1.4fr) minmax(0, 1fr)', alignItems: 'start' }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div className="card card-pad" style={{ display: 'flex', gap: 12, alignItems: 'center', flexWrap: 'wrap' }}>
            <div className="field" style={{ flex: 1, minWidth: 120 }}><label>ปีภาษี</label><select className="select"><option>2568</option><option>2567</option></select></div>
            <div className="field" style={{ flex: 1, minWidth: 120 }}><label>เดือน</label><select className="select" defaultValue="พฤษภาคม"><option>พฤษภาคม</option><option>เมษายน</option><option>มีนาคม</option></select></div>
            <div className="field" style={{ flex: 1, minWidth: 120 }}><label>ส่งถึง</label><select className="select"><option>สนง.บัญชี รุ่งเรือง</option></select></div>
          </div>

          <div className="card">
            <div className="card-head"><h3>ไฟล์ที่จะรวมในแพ็ก</h3></div>
            <div style={{ padding: '8px 6px' }}>
              {items.map((it) => (
                <label key={it.k} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '11px 14px', borderRadius: 10, cursor: 'pointer', transition: '.12s' }}
                  onMouseEnter={(e) => e.currentTarget.style.background = 'var(--surface-2)'} onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}>
                  <input type="checkbox" checked={opts[it.k]} onChange={() => setOpts((o) => ({ ...o, [it.k]: !o[it.k] }))} style={{ accentColor: 'var(--primary)', width: 17, height: 17 }} />
                  <div className="stat-ic" style={{ background: 'var(--surface-2)', color: 'var(--primary)', width: 34, height: 34 }}><Icon name={it.icon} size={17} /></div>
                  <div style={{ flex: 1 }}><div style={{ fontWeight: 600, fontSize: 13.5 }}>{it.label}</div><div className="mono" style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>{it.file} · {it.size}</div></div>
                  {done && opts[it.k] && <button className="btn btn-ghost btn-sm" onClick={(e) => { e.preventDefault(); toast('ดาวน์โหลด ' + it.file); }}><Icon name="download" className="ic" /></button>}
                </label>
              ))}
            </div>
          </div>

          <div className="card card-pad">
            <label style={{ display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer' }}>
              <input type="checkbox" checked={opts.markSent} onChange={() => setOpts((o) => ({ ...o, markSent: !o.markSent }))} style={{ accentColor: 'var(--primary)', width: 17, height: 17 }} />
              <span style={{ fontSize: 13.5, fontWeight: 500 }}>เปลี่ยนสถานะเอกสารทั้งหมดเป็น <b>"ส่งบัญชีแล้ว"</b> หลังสร้างแพ็ก</span>
            </label>
          </div>
        </div>

        {/* summary / folder tree */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16, position: 'sticky', top: 78 }}>
          <div className="card">
            <div className="card-head"><h3>โครงสร้างโฟลเดอร์</h3></div>
            <div className="card-pad mono" style={{ fontSize: 12, lineHeight: 1.9, color: 'var(--ink-2)' }}>
              {['📁 2568/', '  📁 05-พฤษภาคม/', '    📁 รายรับ/', '    📁 รายจ่าย/', '    📁 ภาษีซื้อ/', '    📁 ภาษีขาย/', '    📄 สรุปส่งบัญชี.pdf'].map((l, i) => (
                <div key={i} style={{ paddingLeft: (l.match(/^\s*/)[0].length) * 4, color: l.includes('📄') ? 'var(--primary)' : 'var(--ink-2)' }}>{l.trim()}</div>
              ))}
            </div>
          </div>

          <div className="card card-pad" style={{ textAlign: 'center' }}>
            {!done ? (
              <button className="btn btn-primary btn-lg btn-block" onClick={build} disabled={building}>
                {building ? <><Icon name="refresh" className="ic" style={{ animation: 'spin 1s linear infinite' }} />กำลังเตรียมไฟล์…</> : <><Icon name="package" className="ic" />เตรียมส่งสำนักงานบัญชี</>}
              </button>
            ) : (
              <>
                <div style={{ width: 52, height: 52, borderRadius: '50%', background: 'var(--ok-bg)', color: 'var(--ok)', display: 'grid', placeItems: 'center', margin: '0 auto 12px' }}><Icon name="checkCircle" size={28} /></div>
                <div style={{ fontWeight: 700, fontSize: 15 }}>แพ็กพร้อมส่งแล้ว</div>
                <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginTop: 3 }}>5 ไฟล์ · รวม 14.5 MB</div>
                <button className="btn btn-primary btn-block" style={{ marginTop: 14 }} onClick={() => toast('ดาวน์โหลดแพ็กทั้งหมด (ZIP)')}><Icon name="download" className="ic" />ดาวน์โหลดทั้งหมด</button>
                <button className="btn btn-ghost btn-block" style={{ marginTop: 8 }} onClick={() => toast('ส่งลิงก์ให้ สนง.บัญชี รุ่งเรือง ทางอีเมลแล้ว')}><Icon name="send" className="ic" />ส่งลิงก์ให้นักบัญชี</button>
              </>
            )}
            <style>{`@keyframes spin{to{transform:rotate(360deg)}}`}</style>
          </div>
        </div>
      </div>
    </>
  );
}

window.PersonalPage = PersonalPage;
window.ExportPage = ExportPage;
