/* ============ Annual reports: งบประจำปี / งบดุล / กราฟวิเคราะห์รายปี ============ */
function AnnualPage({ onNav, toast }) {
  const [tab, setTab] = useState('overview'); // overview | jobs | balance | archive
  const years = D.years;
  const cur = years[years.length - 1];

  return (
    <>
      <div className="page-head">
        <div><div className="pt">งบประจำปี &amp; วิเคราะห์</div><div className="ps">สรุปผลประกอบการรายปี · กำไรสะสม · แยกประเภทงาน · งบดุล — เพื่อยื่นภาษีและวางแผนลดหย่อน</div></div>
        <div className="spacer"></div>
        <button className="btn btn-ghost"><Icon name="download" className="ic" />ส่งออกงบการเงิน</button>
      </div>

      <div className="seg" style={{ marginBottom: 18 }}>
        {[['overview', 'ภาพรวมรายปี'], ['jobs', 'แยกประเภทงาน'], ['balance', 'งบดุล/กำไรสะสม'], ['archive', 'เก็บเอกสารรายปี']].map(([id, l]) => (
          <button key={id} className={tab === id ? 'on' : ''} onClick={() => setTab(id)}>{l}</button>
        ))}
      </div>

      {tab === 'overview' && <AnnualOverview years={years} />}
      {tab === 'jobs' && <AnnualJobs years={years} cur={cur} />}
      {tab === 'balance' && <AnnualBalance years={years} />}
      {tab === 'archive' && <AnnualArchive onNav={onNav} toast={toast} />}
    </>
  );
}

/* ----- grouped bar + line: revenue/expense/profit per year ----- */
function AnnualOverview({ years }) {
  const max = Math.max(...years.flatMap((y) => [y.revenue, y.expense])) * 1.1;
  const maxAcc = Math.max(...years.map((y) => y.accProfit)) * 1.1;
  const H = 240;
  // accumulated profit points as percentages (for div-based dots — avoids SVG oval distortion)
  const pts = years.map((y, i) => ({
    x: (i + 0.5) / years.length * 100,
    y: 100 - (y.accProfit / maxAcc) * 100,
    val: y.accProfit,
  }));
  const linePath = pts.map((p, i) => (i ? 'L' : 'M') + p.x + ' ' + p.y).join(' ');

  return (
    <>
      <div className="grid" style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', marginBottom: 16 }}>
        <Stat label="รายได้ปีนี้ (YTD)" icon="income" value={D.baht(years[3].revenue, 0)} delta="เทียบ 3 ปีย้อนหลัง" deltaDir="up" />
        <Stat label="กำไรสุทธิปีนี้" icon="pie" iconBg="var(--ok-bg)" iconColor="var(--ok)" value={D.baht(years[3].netProfit, 0)} />
        <Stat label="กำไรสะสมทั้งหมด" icon="bank" iconBg="var(--primary-tint)" iconColor="var(--primary)" value={D.baht(years[3].accProfit, 0)} sub="ตั้งแต่ปี 2565" />
        <Stat label="ส่วนของผู้ถือหุ้น" icon="building" iconBg="var(--info-bg)" iconColor="var(--info)" value={D.baht(years[3].equity, 0)} />
      </div>

      <div className="card" style={{ marginBottom: 16 }}>
        <div className="card-head"><div><h3>รายได้ · รายจ่าย · กำไรสะสม รายปี</h3><div className="sub">เปรียบเทียบ 4 ปี (พ.ศ. 2565–2568)</div></div>
          <div style={{ marginLeft: 'auto', display: 'flex', gap: 14, flexWrap: 'wrap' }}>
            {[['รายได้', 'var(--primary)'], ['รายจ่าย', 'var(--primary-tint2)'], ['กำไรสะสม', 'var(--warn)']].map(([l, c]) => (
              <span key={l} style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, fontWeight: 600, whiteSpace: 'nowrap' }}><span style={{ width: 11, height: 11, borderRadius: 3, background: c }}></span>{l}</span>
            ))}
          </div>
        </div>
        <div className="card-pad">
          <div style={{ position: 'relative', height: H }}>
            {/* bars */}
            <div style={{ display: 'flex', alignItems: 'flex-end', gap: '4%', height: H, position: 'relative', zIndex: 1 }}>
              {years.map((y, i) => (
                <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8, height: '100%', justifyContent: 'flex-end' }}>
                  <div style={{ display: 'flex', gap: 5, alignItems: 'flex-end', height: '100%', width: '100%', justifyContent: 'center' }}>
                    <div title={'รายได้ ' + D.baht(y.revenue)} style={{ width: '34%', maxWidth: 38, height: (y.revenue / max * 100) + '%', background: 'var(--primary)', borderRadius: '6px 6px 0 0', transition: 'height .6s cubic-bezier(.2,.8,.3,1)', position: 'relative' }}>
                      <span style={{ position: 'absolute', top: -19, left: '50%', transform: 'translateX(-50%)', fontSize: 10.5, fontWeight: 700, color: 'var(--primary-dark)', whiteSpace: 'nowrap' }}>{(y.revenue / 1e6).toFixed(1)}M</span>
                    </div>
                    <div title={'รายจ่าย ' + D.baht(y.expense)} style={{ width: '34%', maxWidth: 38, height: (y.expense / max * 100) + '%', background: 'var(--primary-tint2)', borderRadius: '6px 6px 0 0', transition: 'height .6s' }}></div>
                  </div>
                  <div style={{ fontSize: 12.5, fontWeight: 600, color: y.ytd ? 'var(--ink-3)' : 'var(--ink)' }}>{y.label}</div>
                </div>
              ))}
            </div>
            {/* accumulated profit line overlay */}
            <div style={{ position: 'absolute', inset: 0, bottom: 26, pointerEvents: 'none', zIndex: 2 }}>
              <svg viewBox="0 0 100 100" preserveAspectRatio="none" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', overflow: 'visible' }}>
                <path d={linePath} fill="none" stroke="var(--warn)" strokeWidth="2" vectorEffect="non-scaling-stroke" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
              {pts.map((p, i) => (
                <div key={i} style={{ position: 'absolute', left: p.x + '%', top: p.y + '%', width: 11, height: 11, borderRadius: '50%', background: 'var(--warn)', border: '2.5px solid var(--surface)', transform: 'translate(-50%,-50%)', boxShadow: 'var(--shadow-sm)' }}></div>
              ))}
            </div>
          </div>
        </div>
      </div>

      {/* per-year table */}
      <div className="card">
        <div className="card-head"><h3>ตารางสรุปผลประกอบการรายปี</h3></div>
        <div className="tbl-wrap">
          <table className="tbl">
            <thead><tr><th>ปีภาษี (พ.ศ.)</th><th className="r">รายได้รวม</th><th className="r">รายจ่ายรวม</th><th className="r">กำไรขั้นต้น</th><th className="r">VAT จ่าย</th><th className="r">กำไรสุทธิ</th><th className="r">กำไรสะสม</th></tr></thead>
            <tbody>
              {years.map((y) => (
                <tr key={y.year}>
                  <td style={{ fontWeight: 600 }}>{y.label}{y.ytd && <span className="badge muted" style={{ marginLeft: 7, fontSize: 10 }}>ถึงปัจจุบัน</span>}</td>
                  <td className="r num">{D.fmt0(y.revenue)}</td>
                  <td className="r num" style={{ color: 'var(--ink-2)' }}>{D.fmt0(y.expense)}</td>
                  <td className="r num">{D.fmt0(y.profit)}</td>
                  <td className="r num" style={{ color: 'var(--ink-3)' }}>{D.fmt0(y.vatPaid)}</td>
                  <td className="r num" style={{ fontWeight: 700, color: 'var(--ok)' }}>{D.fmt0(y.netProfit)}</td>
                  <td className="r num" style={{ fontWeight: 600 }}>{D.fmt0(y.accProfit)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </>
  );
}

/* ----- revenue split by job type ----- */
function AnnualJobs({ years, cur }) {
  const segs = D.jobTypes.map((j) => ({ id: j.id, label: j.label, color: j.color, value: cur.revByJob[j.id] || 0 })).sort((a, b) => b.value - a.value);
  const totalCur = segs.reduce((a, s) => a + s.value, 0);
  // stacked bars across years
  const maxYr = Math.max(...years.map((y) => y.revenue)) * 1.05;

  return (
    <>
      <div className="callout info" style={{ marginBottom: 16 }}><Icon name="sparkle" className="ic" /><div>วิเคราะห์ว่ารายได้มาจากงานประเภทใดบ้าง เพื่อ<b>วางแผนภาษีและจับคู่ใบกำกับภาษีซื้อ</b>ให้ตรงประเภทงาน — ใช้สิทธิ์ลดหย่อน/เครดิต VAT ได้ถูกต้อง</div></div>

      <div className="grid" style={{ gridTemplateColumns: 'minmax(0, 1fr) minmax(0, 1.3fr)', marginBottom: 16, alignItems: 'start' }}>
        <div className="card">
          <div className="card-head"><h3>สัดส่วนรายได้ปีนี้</h3><span className="badge muted" style={{ marginLeft: 'auto' }}>{cur.label}</span></div>
          <div className="card-pad" style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 16 }}>
            <Donut segments={segs} size={190} centerLabel={D.baht(totalCur / 1e6, 1) + 'M'} centerSub="รายได้รวม" />
            <div style={{ width: '100%', display: 'flex', flexDirection: 'column', gap: 9 }}>
              {segs.map((s) => (
                <div key={s.id} style={{ display: 'flex', alignItems: 'center', gap: 9, fontSize: 13 }}>
                  <span style={{ width: 10, height: 10, borderRadius: 3, background: s.color, flexShrink: 0 }}></span>
                  <span style={{ flex: 1 }}>{s.label}</span>
                  <span className="num" style={{ fontWeight: 600 }}>{D.fmt0(s.value)}</span>
                  <span style={{ fontSize: 11.5, color: 'var(--ink-3)', width: 42, textAlign: 'right' }}>{Math.round(s.value / totalCur * 100)}%</span>
                </div>
              ))}
            </div>
          </div>
        </div>

        <div className="card">
          <div className="card-head"><h3>แนวโน้มรายได้แต่ละประเภทงาน</h3><div className="sub">stacked · 4 ปี</div></div>
          <div className="card-pad">
            <div style={{ display: 'flex', alignItems: 'flex-end', gap: '5%', height: 260 }}>
              {years.map((y) => {
                const total = y.revenue;
                return (
                  <div key={y.year} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8, height: '100%', justifyContent: 'flex-end' }}>
                    <div style={{ width: '100%', maxWidth: 60, height: (total / maxYr * 100) + '%', borderRadius: '6px 6px 0 0', overflow: 'hidden', display: 'flex', flexDirection: 'column', boxShadow: 'var(--shadow-sm)' }}>
                      {D.jobTypes.map((j) => {
                        const v = y.revByJob[j.id] || 0;
                        return <div key={j.id} title={j.label + ' ' + D.baht(v)} style={{ height: (v / total * 100) + '%', background: j.color, transition: 'height .6s' }}></div>;
                      })}
                    </div>
                    <div style={{ fontSize: 12, fontWeight: 600, color: y.ytd ? 'var(--ink-3)' : 'var(--ink)' }}>{y.label.split(' ')[0]}</div>
                  </div>
                );
              })}
            </div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px 14px', marginTop: 16, paddingTop: 14, borderTop: '1px solid var(--line-2)' }}>
              {D.jobTypes.map((j) => (
                <span key={j.id} style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 11.5, fontWeight: 500 }}><span style={{ width: 9, height: 9, borderRadius: 2, background: j.color }}></span>{j.label}</span>
              ))}
            </div>
          </div>
        </div>
      </div>

      {/* matrix table: job type x year */}
      <div className="card">
        <div className="card-head"><h3>รายได้แยกประเภทงาน × ปี</h3></div>
        <div className="tbl-wrap">
          <table className="tbl">
            <thead><tr><th>ประเภทงาน</th>{years.map((y) => <th key={y.year} className="r">{y.label.split(' ')[0]}</th>)}<th className="r">รวม 4 ปี</th></tr></thead>
            <tbody>
              {D.jobTypes.map((j) => {
                const sum = years.reduce((a, y) => a + (y.revByJob[j.id] || 0), 0);
                return (
                  <tr key={j.id}>
                    <td style={{ fontWeight: 500 }}><span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}><span style={{ width: 9, height: 9, borderRadius: 2, background: j.color }}></span>{j.label}</span></td>
                    {years.map((y) => <td key={y.year} className="r num">{D.fmt0(y.revByJob[j.id] || 0)}</td>)}
                    <td className="r num" style={{ fontWeight: 700 }}>{D.fmt0(sum)}</td>
                  </tr>
                );
              })}
            </tbody>
            <tfoot><tr style={{ background: 'var(--surface-2)', fontWeight: 700 }}>
              <td style={{ padding: 12 }}>รวมรายได้</td>
              {years.map((y) => <td key={y.year} className="r num" style={{ padding: 12 }}>{D.fmt0(y.revenue)}</td>)}
              <td className="r num" style={{ padding: 12 }}>{D.fmt0(years.reduce((a, y) => a + y.revenue, 0))}</td>
            </tr></tfoot>
          </table>
        </div>
      </div>
    </>
  );
}

/* ----- balance sheet + accumulated profit ----- */
function AnnualBalance({ years }) {
  const cur = years[years.length - 1];
  const maxAcc = Math.max(...years.map((y) => y.accProfit));
  return (
    <>
      <div className="grid" style={{ gridTemplateColumns: 'minmax(0, 1fr) minmax(0, 1fr)', marginBottom: 16, alignItems: 'start' }}>
        {/* balance sheet */}
        <div className="card">
          <div className="card-head"><div><h3>งบดุล (ย่อ)</h3><div className="sub">ณ สิ้นปี {cur.label}</div></div></div>
          <div className="card-pad" style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
            <BalRow label="สินทรัพย์รวม" value={cur.assets} bold />
            <BalSub label="เงินสด/ลูกหนี้/สินค้าคงเหลือ" value={cur.assets * 0.42} />
            <BalSub label="ที่ดิน อาคาร เครื่องจักร" value={cur.assets * 0.58} />
            <div className="divider"></div>
            <BalRow label="หนี้สินรวม" value={cur.liabilities} bold />
            <BalSub label="เจ้าหนี้การค้า/ค้างจ่าย" value={cur.liabilities * 0.55} />
            <BalSub label="เงินกู้ระยะยาว" value={cur.liabilities * 0.45} />
            <div className="divider"></div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '13px 14px', background: 'var(--primary-tint)', borderRadius: 10, marginTop: 4 }}>
              <span style={{ fontWeight: 700 }}>ส่วนของผู้ถือหุ้น</span>
              <span className="num" style={{ fontWeight: 700, fontSize: 18, color: 'var(--primary-dark)' }}>{D.baht(cur.equity, 0)}</span>
            </div>
            <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 8, textAlign: 'center' }}>สินทรัพย์ = หนี้สิน + ส่วนของผู้ถือหุ้น</div>
          </div>
        </div>

        {/* accumulated profit growth */}
        <div className="card">
          <div className="card-head"><h3>กำไรสะสม (เติบโตรายปี)</h3></div>
          <div className="card-pad">
            <div style={{ display: 'flex', alignItems: 'flex-end', gap: '6%', height: 200, marginBottom: 8 }}>
              {years.map((y) => (
                <div key={y.year} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8, height: '100%', justifyContent: 'flex-end' }}>
                  <span className="num" style={{ fontSize: 11, fontWeight: 700, color: 'var(--primary-dark)' }}>{(y.accProfit / 1e6).toFixed(1)}M</span>
                  <div style={{ width: '100%', maxWidth: 46, height: (y.accProfit / maxAcc * 100) + '%', background: 'linear-gradient(180deg, var(--primary), var(--primary-dark))', borderRadius: '6px 6px 0 0', transition: 'height .6s cubic-bezier(.2,.8,.3,1)' }}></div>
                  <div style={{ fontSize: 12, fontWeight: 600, color: y.ytd ? 'var(--ink-3)' : 'var(--ink)' }}>{y.label.split(' ')[0]}</div>
                </div>
              ))}
            </div>
          </div>
          <div style={{ padding: '0 18px 18px' }}>
            <div className="callout info" style={{ padding: '10px 13px' }}><Icon name="info" className="ic" /><div>กำไรสะสมใช้พิจารณาการจ่ายเงินปันผลและประเมินสุขภาพทางการเงินของกิจการ</div></div>
          </div>
        </div>
      </div>

      {/* P&L summary for filing */}
      <div className="card">
        <div className="card-head"><div><h3>งบกำไรขาดทุน — เตรียมยื่นภาษี</h3><div className="sub">สรุปสำหรับ ภ.ง.ด.50 (นิติบุคคล)</div></div>
          <button className="btn btn-sm btn-soft" style={{ marginLeft: 'auto' }}><Icon name="download" className="ic" />ส่งบัญชี</button>
        </div>
        <div className="tbl-wrap">
          <table className="tbl">
            <thead><tr><th>รายการ</th>{years.map((y) => <th key={y.year} className="r">{y.label.split(' ')[0]}</th>)}</tr></thead>
            <tbody>
              <tr><td style={{ fontWeight: 500 }}>รายได้จากการประกอบกิจการ</td>{years.map((y) => <td key={y.year} className="r num">{D.fmt0(y.revenue)}</td>)}</tr>
              <tr><td style={{ color: 'var(--ink-2)' }}>หัก ต้นทุน + ค่าใช้จ่าย</td>{years.map((y) => <td key={y.year} className="r num" style={{ color: 'var(--ink-2)' }}>({D.fmt0(y.expense)})</td>)}</tr>
              <tr style={{ background: 'var(--surface-2)' }}><td style={{ fontWeight: 600 }}>กำไรก่อนภาษี</td>{years.map((y) => <td key={y.year} className="r num" style={{ fontWeight: 600 }}>{D.fmt0(y.profit)}</td>)}</tr>
              <tr><td style={{ fontWeight: 700 }}>กำไรสุทธิ</td>{years.map((y) => <td key={y.year} className="r num" style={{ fontWeight: 700, color: 'var(--ok)' }}>{D.fmt0(y.netProfit)}</td>)}</tr>
            </tbody>
          </table>
        </div>
      </div>
    </>
  );
}
function BalRow({ label, value, bold }) {
  return <div style={{ display: 'flex', justifyContent: 'space-between', padding: '8px 0', fontWeight: bold ? 700 : 500, fontSize: bold ? 14.5 : 13.5 }}><span>{label}</span><span className="num">{D.baht(value, 0)}</span></div>;
}
function BalSub({ label, value }) {
  return <div style={{ display: 'flex', justifyContent: 'space-between', padding: '5px 0 5px 14px', fontSize: 12.5, color: 'var(--ink-2)' }}><span>{label}</span><span className="num">{D.fmt0(value)}</span></div>;
}

/* ----- document archive per year ----- */
function AnnualArchive({ onNav, toast }) {
  return (
    <>
      <div className="callout info" style={{ marginBottom: 16 }}><Icon name="folder" className="ic" /><div>คลังเก็บเอกสารแยกตามปี — ทุกใบเสร็จ/ใบกำกับภาษีถูกจัดเก็บถาวร แบ่งโฟลเดอร์ <span className="mono">/ปี/เดือน/หมวด</span> พร้อมดาวน์โหลดทั้งปีได้</div></div>
      <div className="grid" style={{ gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))' }}>
        {D.archives.map((a) => (
          <div key={a.year} className="card" style={{ overflow: 'hidden' }}>
            <div style={{ padding: '16px 18px', display: 'flex', alignItems: 'center', gap: 12, borderBottom: '1px solid var(--line-2)' }}>
              <div className="stat-ic" style={{ width: 42, height: 42, background: a.status === 'active' ? 'var(--primary-tint)' : 'var(--surface-2)', color: a.status === 'active' ? 'var(--primary)' : 'var(--ink-2)', borderRadius: 11 }}><Icon name="folder" size={21} /></div>
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 700, fontSize: 16 }}>ปี {a.year}</div>
                <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{a.months} เดือน · {a.docs} เอกสาร</div>
              </div>
              {a.status === 'active' ? <span className="badge ok"><span className="dot"></span>ปีปัจจุบัน</span> : a.status === 'complete' ? <span className="badge info">ครบถ้วน</span> : <span className="badge muted">เก็บถาวร</span>}
            </div>
            <div className="card-pad" style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
              <div style={{ display: 'flex', gap: 8 }}>
                <div style={{ flex: 1, background: 'var(--surface-2)', borderRadius: 9, padding: '9px 11px' }}><div style={{ fontSize: 11, color: 'var(--ink-3)' }}>รายรับ</div><div className="num" style={{ fontWeight: 700 }}>{a.income}</div></div>
                <div style={{ flex: 1, background: 'var(--surface-2)', borderRadius: 9, padding: '9px 11px' }}><div style={{ fontSize: 11, color: 'var(--ink-3)' }}>รายจ่าย</div><div className="num" style={{ fontWeight: 700 }}>{a.expense}</div></div>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12.5, color: 'var(--ink-2)', paddingTop: 2 }}><span>ส่งบัญชีแล้ว</span><span style={{ fontWeight: 600 }}>{a.sent}/{a.months} เดือน</span></div>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12.5, color: 'var(--ink-2)' }}><span>ขนาดไฟล์รวม</span><span className="mono" style={{ fontWeight: 600 }}>{a.size}</span></div>
              <div style={{ display: 'flex', gap: 8, marginTop: 6 }}>
                <button className="btn btn-ghost btn-sm" style={{ flex: 1 }} onClick={() => onNav('docs')}><Icon name="eye" className="ic" />ดูเอกสาร</button>
                <button className="btn btn-soft btn-sm" style={{ flex: 1 }} onClick={() => toast('กำลังสร้าง ZIP เอกสารปี ' + a.year + '…')}><Icon name="download" className="ic" />ทั้งปี (ZIP)</button>
              </div>
            </div>
          </div>
        ))}
      </div>
    </>
  );
}

window.AnnualPage = AnnualPage;
