// 출력 뷰: 갑지 / 원가계산서 / 상세견적서  (아정당인테리어 양식)  window.EstOutput
const { won, hangulMoney } = window.EstCalc;
const oORDER = window.GONGJONG_ORDER;
const dash = (n) => (n ? won(n) : '-');

const oStyles = {
  page: {
    width: '900px', margin: '0 auto 22px', background: '#fff',
    border: '1px solid var(--line)', boxShadow: 'var(--shadow)',
    padding: '46px 50px', color: 'var(--ink)', fontSize: '12.5px',
  },
};
const bd = '1px solid oklch(0.78 0.01 260)';
const th = { border: bd, background: 'var(--surface-2)', padding: '6px 7px', fontWeight: 700, fontSize: '11.5px', textAlign: 'center', color: 'var(--ink-2)' };
const td = { border: bd, padding: '5px 8px', fontSize: '12px', verticalAlign: 'middle' };
const tdR = { ...td, textAlign: 'right', fontFamily: 'var(--mono)', fontFeatureSettings: '"tnum" 1', fontVariantNumeric: 'tabular-nums' };
const tdC = { ...td, textAlign: 'center' };

function getCompany(est) { return Object.assign({}, window.COMPANY_DEFAULT, est.company || {}); }
function getRemarks(est) { return est.remarks != null ? est.remarks : window.REMARKS_DEFAULT; }
function gNo(g) { const i = oORDER.indexOf(g); return i < 0 ? 99 : i + 1; }

/* ================= 갑지 ================= */
function CoverPage({ est, c }) {
  const co = getCompany(est);
  const remarks = getRemarks(est);
  return (
    <div className="est-page" style={oStyles.page} data-screen-label="갑지">
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 16 }}>
        <img src="symbol.svg" alt="아정당" style={{ height: 26, width: 'auto' }} />
        <span style={{ fontWeight: 800, fontSize: 19, color: 'var(--accent-ink)', letterSpacing: '-0.01em', position: 'relative', top: '-4px' }}>아정당인테리어</span>
      </div>
      <div style={{ textAlign: 'center', marginBottom: 26, borderBottom: '3px solid var(--accent)', paddingBottom: 14 }}>
        <div style={{ fontSize: 32, fontWeight: 800, letterSpacing: 10, color: 'var(--accent-ink)' }}>가&nbsp;견&nbsp;적&nbsp;서</div>
        <div style={{ fontSize: 12, letterSpacing: 6, color: 'var(--ink-3)', fontWeight: 600, marginTop: 2 }}>PRELIMINARY ESTIMATE</div>
      </div>

      <table style={{ width: '100%', borderCollapse: 'collapse' }}>
        <tbody>
          <CovRow label="◑ 날짜 / DATE" value={fmtKDate(est.site.date)} />
          <CovRow label="◑ 공사명 / PROJECT" value={est.site.name || '현장명 미입력'} strong />
          <tr>
            <td style={{ ...td, width: 190, background: 'var(--surface-2)', fontWeight: 700 }}>◑ 견적금액 / AMOUNT</td>
            <td style={{ ...td, padding: '12px 14px' }}>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, flexWrap: 'wrap' }}>
                <span className="mono" style={{ fontSize: 24, fontWeight: 800, color: 'var(--accent-ink)' }}>₩ {won(c.final)}</span>
                <span style={{ fontSize: 13, fontWeight: 700 }}>(일금 {hangulMoney(c.final)}정)</span>
                <span style={{ fontSize: 12, color: 'var(--ink)', fontWeight: 700 }}>(V.A.T 별도)</span>
              </div>
            </td>
          </tr>
        </tbody>
      </table>

      <div style={{ marginTop: 22, fontSize: 13, lineHeight: 1.7 }}>
        별첨 명세와 같이 견적서를 제출합니다.
        <div style={{ fontSize: 11, color: 'var(--ink-3)', letterSpacing: '.02em' }}>WE ARE PLEASED TO SUBMIT YOU ESTIMATE AS SPECIFIED ON ATTACHED SHEETS.</div>
      </div>
      <div style={{ marginTop: 14, fontSize: 11, color: 'var(--ink-3)' }}>※ 본 견적서는 대외비 문서로, 당사의 승인 없는 무단 배포 및 제3자 공유를 금지합니다.</div>

      <div style={{ marginTop: 22, border: bd, borderRadius: 2 }}>
        <div style={{ background: 'var(--surface-2)', borderBottom: bd, padding: '7px 12px', fontWeight: 700, fontSize: 12.5 }}>▶ 비고 (REMARKS)</div>
        <div style={{ padding: '12px 14px', fontSize: 12, color: 'var(--ink-2)', lineHeight: 1.8, whiteSpace: 'pre-wrap' }}>{remarks}</div>
      </div>

      {(est.purchases || []).filter((p) => p.name && p.name.trim()).length > 0 && (
        <div style={{ marginTop: 16, border: bd, borderRadius: 2 }}>
          <div style={{ background: 'var(--surface-2)', borderBottom: bd, padding: '7px 12px', fontWeight: 700, fontSize: 12.5 }}>🛒 물품 구매 대행 (별도 안내)</div>
          <div style={{ padding: '10px 14px', fontSize: 12, color: 'var(--ink-2)', lineHeight: 1.7 }}>
            {est.purchases.filter((p) => p.name && p.name.trim()).map((p) => p.name.trim()).join(' · ')}
            <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 4 }}>※ 위 품목은 인테리어 공사 견적과 별도로 구매 대행해 드리는 항목이며, 위 견적금액에는 포함되지 않습니다.</div>
          </div>
        </div>
      )}

      <div style={{ marginTop: 40, display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end' }}>
        <div style={{ fontSize: 11.5, color: 'var(--ink-2)', lineHeight: 1.7 }}>
          <div>건설업등록번호 : {co.regno}</div>
          <div>주 소 : {co.addr}</div>
          {co.tel ? <div>TEL : {co.tel}</div> : null}
        </div>
        <div style={{ textAlign: 'right' }}>
          <div style={{ fontSize: 12, color: 'var(--ink-3)', letterSpacing: 4 }}>내역서 / ESTIMATE</div>
          <div style={{ fontSize: 19, fontWeight: 800, marginTop: 4 }}>{co.name}</div>
          <div style={{ fontSize: 13, marginTop: 6, display: 'flex', alignItems: 'center', justifyContent: 'flex-end', gap: 8 }}>
            <span>대 표 : {co.reps}</span>
            <img src="도장.png" alt="(인)" style={{ height: 46, width: 'auto' }} />
          </div>
        </div>
      </div>
    </div>
  );
}
function CovRow({ label, value, strong }) {
  return (
    <tr>
      <td style={{ ...td, width: 190, background: 'var(--surface-2)', fontWeight: 700 }}>{label}</td>
      <td style={{ ...td, fontWeight: strong ? 700 : 500, fontSize: strong ? 14 : 12.5 }}>{value}</td>
    </tr>
  );
}

/* ================= 원가계산서 ================= */
function SummaryPage({ est, c }) {
  const co = getCompany(est);
  const visible = c.groups.filter((g) => g.rows.length).sort((a, b) => gNo(a.gongjong) - gNo(b.gongjong));
  return (
    <div className="est-page" style={oStyles.page} data-screen-label="원가계산서">
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', borderBottom: '2px solid var(--accent)', paddingBottom: 8, marginBottom: 12 }}>
        <div style={{ fontSize: 20, fontWeight: 800, color: 'var(--accent-ink)' }}>■ 원가계산서</div>
        <img src="symbol.svg" alt="아정당" style={{ height: 22, width: 'auto' }} />
      </div>
      <table style={{ width: '100%', borderCollapse: 'collapse', marginBottom: 14 }}>
        <tbody>
          <tr>
            <td style={{ ...td, width: 110, background: 'var(--surface-2)', fontWeight: 700 }}>공사명</td>
            <td style={td}>{est.site.name}</td>
            <td style={{ ...td, width: 110, background: 'var(--surface-2)', fontWeight: 700 }}>견적 의뢰일</td>
            <td style={tdC}>{fmtKDate(est.site.reqDate || est.site.date)}</td>
          </tr>
          <tr>
            <td style={{ ...td, background: 'var(--surface-2)', fontWeight: 700 }}>현장주소</td>
            <td style={td}>{est.site.addr}</td>
            <td style={{ ...td, background: 'var(--surface-2)', fontWeight: 700 }}>견적서 유효기한</td>
            <td style={tdC}>{fmtKDate(est.site.validDate) || est.site.valid || '견적일로부터 2주'}</td>
          </tr>
        </tbody>
      </table>

      {/* 공종별 집계 */}
      <table style={{ width: '100%', borderCollapse: 'collapse' }}>
        <thead>
          <tr>
            <th style={{ ...th, width: 78 }}>구분</th>
            <th style={{ ...th, width: 34 }}>No</th>
            <th style={{ ...th, textAlign: 'left' }}>품 목</th>
            <th style={{ ...th, width: 40 }}>단위</th>
            <th style={{ ...th, width: 40 }}>수량</th>
            <th style={{ ...th, width: 110 }}>재료비</th>
            <th style={{ ...th, width: 110 }}>노무비</th>
            <th style={{ ...th, width: 120 }}>소 계</th>
          </tr>
        </thead>
        <tbody>
          {visible.map((g, i) => (
            <tr key={g.gongjong}>
              {i === 0 && <td style={{ ...tdC, fontWeight: 700, background: 'var(--surface-2)' }} rowSpan={visible.length}>공사비</td>}
              <td style={tdC}>{gNo(g.gongjong)}</td>
              <td style={{ ...td, fontWeight: 600 }}>{g.gongjong}</td>
              <td style={tdC}>식</td>
              <td style={tdC}>1</td>
              <td style={tdR}>{dash(g.matSum)}</td>
              <td style={tdR}>{dash(g.labSum)}</td>
              <td style={{ ...tdR, fontWeight: 700 }}>{won(g.total)}</td>
            </tr>
          ))}
          <tr>
            <td colSpan={5} style={{ ...td, textAlign: 'center', fontWeight: 800, background: 'var(--surface-2)' }}>직접공사비 소계</td>
            <td style={{ ...tdR, fontWeight: 700, background: 'var(--surface-2)' }}>{won(c.matTotal)}</td>
            <td style={{ ...tdR, fontWeight: 700, background: 'var(--surface-2)' }}>{won(c.labTotal)}</td>
            <td style={{ ...tdR, fontWeight: 800, background: 'var(--surface-2)' }}>{won(c.direct)}</td>
          </tr>
        </tbody>
      </table>

      {/* 간접공사비 */}
      <table style={{ width: '100%', borderCollapse: 'collapse', marginTop: 16 }}>
        <thead>
          <tr>
            <th style={{ ...th, width: 78 }}>구분</th>
            <th style={{ ...th, width: 34 }}>No</th>
            <th style={{ ...th, textAlign: 'left' }}>항 목</th>
            <th style={{ ...th, textAlign: 'left' }}>산출 근거</th>
            <th style={{ ...th, width: 130 }}>금 액</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td style={{ ...tdC, fontWeight: 700, background: 'var(--surface-2)' }} rowSpan={c.expenses.length + 1}>간접<br />공사비</td>
            <td style={tdC}>1</td>
            <td style={{ ...td, fontWeight: 600 }}>하자보증보험</td>
            <td style={{ ...td, color: 'var(--ink-3)' }}>무료 서비스 가입</td>
            <td style={tdR}>-</td>
          </tr>
          {c.expenses.map((e, i) => (
            <tr key={e.key} style={{ opacity: e.enabled ? 1 : .45 }}>
              <td style={tdC}>{i + 2}</td>
              <td style={{ ...td, fontWeight: 600 }}>{e.label}</td>
              <td style={{ ...td, color: 'var(--ink-3)' }}>{e.note}</td>
              <td style={tdR}>{e.enabled ? dash(e.amt) : '제외'}</td>
            </tr>
          ))}
        </tbody>
        <tbody>
          <tr>
            <td colSpan={4} style={{ ...td, textAlign: 'center', fontWeight: 800, background: 'var(--surface-2)' }}>간접공사비 합계</td>
            <td style={{ ...tdR, fontWeight: 800, background: 'var(--surface-2)' }}>{won(c.expenseTotal)}</td>
          </tr>
        </tbody>
      </table>

      {/* 합계 산출 */}
      <table style={{ width: '100%', borderCollapse: 'collapse', marginTop: 16 }}>
        <tbody>
          <FinRow k="공사비계" note="공통공사비 + 직접공사비 + 간접공사비" v={c.gongsabikye} />
          <FinRow k="기업이윤" note={`직접공사비의 ${c.profitRate}%`} v={c.profit} />
          <FinRow k="합계" note="공사비계 + 기업이윤" v={c.hap} bold />
          <FinRow k="합계 (만원단위 절사)" note={c.nego ? `절사 / NEGO ${won(c.nego)}` : '공사비계 + 기업이윤 + NEGO'} v={c.supply} />
          <FinRow k="부가세 (V.A.T)" note="공급가액 × 10%" v={c.vat} />
          <tr>
            <td style={{ ...td, fontWeight: 800, fontSize: 15, background: 'var(--accent-soft)' }}>총금액 <span style={{ fontSize: 11, fontWeight: 600, color: 'var(--ink-2)' }}>(부가세 포함)</span></td>
            <td style={{ ...td, background: 'var(--accent-soft)' }}></td>
            <td style={{ ...tdR, fontWeight: 800, fontSize: 18, color: 'var(--accent-ink)', background: 'var(--accent-soft)' }}>₩ {won(c.grand)}</td>
          </tr>
        </tbody>
      </table>
    </div>
  );
}
function FinRow({ k, note, v, bold }) {
  return (
    <tr>
      <td style={{ ...td, width: 220, fontWeight: bold ? 800 : 700, background: 'var(--surface-2)' }}>{k}</td>
      <td style={{ ...td, color: 'var(--ink-3)', fontSize: 11.5 }}>{note}</td>
      <td style={{ ...tdR, width: 150, fontWeight: bold ? 800 : 700 }}>{won(v)}</td>
    </tr>
  );
}

/* ================= 상세 견적서 ================= */
function DetailPage({ est, c }) {
  const visible = c.groups.filter((g) => g.rows.length).sort((a, b) => gNo(a.gongjong) - gNo(b.gongjong));
  return (
    <div className="est-page" style={oStyles.page} data-screen-label="상세견적서">
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', borderBottom: '2px solid var(--accent)', paddingBottom: 8, marginBottom: 12 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <img src="symbol.svg" alt="아정당" style={{ height: 22, width: 'auto' }} />
          <div style={{ fontSize: 20, fontWeight: 800, color: 'var(--accent-ink)' }}>■ 상세 견적서</div>
        </div>
        <div style={{ fontSize: 12, color: 'var(--ink-2)' }}>{est.site.name} · {est.site.date}</div>
      </div>
      <table style={{ width: '100%', borderCollapse: 'collapse' }}>
        <thead>
          <tr>
            <th style={{ ...th, width: 78 }} rowSpan={2}>구분</th>
            <th style={{ ...th, textAlign: 'left' }} rowSpan={2}>상세 내용</th>
            <th style={{ ...th, width: 38 }} rowSpan={2}>단위</th>
            <th style={{ ...th, width: 40 }} rowSpan={2}>수량</th>
            <th style={{ ...th }} colSpan={2}>재 료 비</th>
            <th style={{ ...th }} colSpan={2}>노 무 비</th>
            <th style={{ ...th, width: 96 }} rowSpan={2}>소 계</th>
            <th style={{ ...th, width: 90, textAlign: 'left' }} rowSpan={2}>비고</th>
          </tr>
          <tr>
            <th style={{ ...th, width: 78 }}>단가</th>
            <th style={{ ...th, width: 88 }}>금액</th>
            <th style={{ ...th, width: 78 }}>단가</th>
            <th style={{ ...th, width: 88 }}>금액</th>
          </tr>
        </thead>
        <tbody>
          {visible.map((g) => (
            <React.Fragment key={g.gongjong}>
              <tr>
                <td colSpan={10} style={{ ...td, fontWeight: 800, background: 'var(--accent-soft)', color: 'var(--accent-ink)' }}>{gNo(g.gongjong)}. {g.gongjong}</td>
              </tr>
              {g.rows.map((r, i) => (
                <tr key={i}>
                  <td style={{ ...td, color: 'var(--ink-2)' }}>{r.gubun || ''}</td>
                  <td style={td}>{r.name}</td>
                  <td style={tdC}>{r.unit}</td>
                  <td style={tdR}>{r.qty}</td>
                  <td style={tdR}>{dash(r.mat ? Math.round(r.mat) : 0)}</td>
                  <td style={tdR}>{dash(r.matAmt)}</td>
                  <td style={tdR}>{dash(r.lab ? Math.round(r.lab) : 0)}</td>
                  <td style={tdR}>{dash(r.labAmt)}</td>
                  <td style={{ ...tdR, fontWeight: 700 }}>{won(r.total)}</td>
                  <td style={{ ...td, fontSize: 11, color: 'var(--ink-3)' }}>{r.note || ''}</td>
                </tr>
              ))}
              <tr>
                <td colSpan={4} style={{ ...td, textAlign: 'center', fontWeight: 700, background: 'var(--surface-2)' }}>소 계</td>
                <td style={{ ...td, background: 'var(--surface-2)' }}></td>
                <td style={{ ...tdR, fontWeight: 700, background: 'var(--surface-2)' }}>{dash(g.matSum)}</td>
                <td style={{ ...td, background: 'var(--surface-2)' }}></td>
                <td style={{ ...tdR, fontWeight: 700, background: 'var(--surface-2)' }}>{dash(g.labSum)}</td>
                <td style={{ ...tdR, fontWeight: 800, background: 'var(--surface-2)' }}>{won(g.total)}</td>
                <td style={{ ...td, background: 'var(--surface-2)' }}></td>
              </tr>
            </React.Fragment>
          ))}
          <tr>
            <td colSpan={4} style={{ ...td, textAlign: 'center', fontWeight: 800, background: 'var(--accent)', color: '#fff' }}>직접공사비 합계</td>
            <td style={{ ...td, background: 'var(--accent)' }}></td>
            <td style={{ ...tdR, fontWeight: 800, background: 'var(--accent)', color: '#fff' }}>{won(c.matTotal)}</td>
            <td style={{ ...td, background: 'var(--accent)' }}></td>
            <td style={{ ...tdR, fontWeight: 800, background: 'var(--accent)', color: '#fff' }}>{won(c.labTotal)}</td>
            <td style={{ ...tdR, fontWeight: 800, background: 'var(--accent)', color: '#fff' }}>{won(c.direct)}</td>
            <td style={{ ...td, background: 'var(--accent)' }}></td>
          </tr>
        </tbody>
      </table>
    </div>
  );
}

function fmtKDate(s) {
  if (!s) return '';
  const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(s);
  if (!m) return s;
  return `${m[1]}년 ${m[2]}월 ${m[3]}일`;
}

window.EstOutput = { CoverPage, SummaryPage, DetailPage };
