'use client';

/**
 * 출고 문서 공통 컴포넌트 (기획서 D1.8 기준 리디자인)
 * - 출고증: showDispatchInfo + showLotColumn
 * - 납품확인서: 기본값 (배차정보 없음, LOT 컬럼 없음)
 * - BOM 데이터는 orderDetail props로 전달 (수주서와 동일 API 활용)
 */

import { useState } from 'react';
import type { ShipmentDetail } from '../types';
import { DELIVERY_METHOD_LABELS } from '../types';
import { ConstructionApprovalTable } from '@/components/document-system';
import { formatNumber } from '@/lib/utils/amount';

// ===== BOM 데이터 타입 (수주서와 동일) =====

interface ProductRow {
  no: number;
  floor?: string;
  symbol?: string;
  product_name?: string;
  product_code?: string;
  product_type?: string;
  open_width?: number | string;
  open_height?: number | string;
  made_width?: number | string;
  made_height?: number | string;
  guide_rail?: string;
  shaft?: string | number;
  case_inch?: string | number;
  bracket?: string;
  capacity?: string | number;
  finish?: string;
  joint_bar?: number | null;
}

interface MotorRow {
  item: string;
  type: string;
  spec: string;
  qty: number;
  lot?: string;
}

interface BendingItem {
  name: string;
  spec: string;
  qty: number;
}

interface BendingGroup {
  group: string;
  items: BendingItem[];
}

interface SubsidiaryItem {
  name: string;
  spec: string;
  qty: number;
}

export interface OrderDocumentDetail {
  products?: ProductRow[];
  motors?: { left?: MotorRow[]; right?: MotorRow[] };
  bending_parts?: BendingGroup[];
  subsidiary_parts?: SubsidiaryItem[];
  category_code?: string;
  // 수주 기본 정보
  order_no?: string;
  received_at?: string;
  delivery_date?: string;
  client_name?: string;
  client_contact?: string;
  manager_name?: string;
  receiver?: string;
  receiver_contact?: string;
  shipping_address?: string;
  shipping_address_detail?: string;
}

interface ShipmentOrderDocumentProps {
  title: string;
  data: ShipmentDetail;
  orderDetail?: OrderDocumentDetail | null;
  showDispatchInfo?: boolean;
  showLotColumn?: boolean;
}

// ===== 공통 스타일 =====
const thBase = 'border-r border-gray-400 px-1 py-1';
const tdBase = 'border-r border-gray-300 px-1 py-1';
const tdCenter = `${tdBase} text-center`;
const imgPlaceholder = 'flex items-center justify-center border border-dashed border-gray-300 text-gray-400';

export function ShipmentOrderDocument({ title, data, orderDetail, showDispatchInfo = false, showLotColumn = false }: ShipmentOrderDocumentProps) {
  const [bottomFinishView, setBottomFinishView] = useState<'screen' | 'steel'>('screen');

  const deliveryMethodLabel = DELIVERY_METHOD_LABELS[data.deliveryMethod] || '-';
  const fullAddress = [data.address, data.addressDetail].filter(Boolean).join(' ') || data.deliveryAddress || '-';

  // BOM 데이터 (orderDetail에서 추출)
  const productRows = orderDetail?.products || [];
  const motorsLeft = orderDetail?.motors?.left || [];
  const motorsRight = orderDetail?.motors?.right || [];
  const bendingParts = orderDetail?.bending_parts || [];
  const subsidiaryParts = orderDetail?.subsidiary_parts || [];

  const motorRows = Math.max(motorsLeft.length, motorsRight.length);

  // 스크린/철재 제품 분리
  const screenProducts = productRows.filter(p => p.product_type !== 'steel');
  const steelProducts = productRows.filter(p => p.product_type === 'steel');

  // 절곡물 그룹 데이터 추출
  const guideRailItems = bendingParts.find(g => g.group === '가이드레일')?.items ?? [];
  const caseItems = bendingParts.find(g => g.group === '케이스')?.items ?? [];
  const bottomItems = bendingParts.find(g => g.group === '하단마감')?.items ?? [];
  const smokeItems = bendingParts.find(g => g.group === '연기차단재')?.items ?? [];
  const guideSmokeItems = smokeItems.filter(i => i.name.includes('레일') || i.name.includes('가이드'));
  const caseSmokeItems = smokeItems.filter(i => i.name.includes('케이스'));
  const otherSmokeItems = smokeItems.filter(i =>
    !i.name.includes('레일') && !i.name.includes('가이드') && !i.name.includes('케이스')
  );

  // 부자재 좌/우 2열 변환
  const subsidiaryRows = [];
  for (let i = 0; i < subsidiaryParts.length; i += 2) {
    subsidiaryRows.push({
      left: subsidiaryParts[i],
      right: subsidiaryParts[i + 1] ?? null,
    });
  }

  // 셔터 수량: productRows 기준 (없으면 productGroups fallback)
  const shutterCount = productRows.length || data.productGroups.length;

  return (
    <div className="bg-white p-8 min-h-full text-[11px]">
      {/* ========== 헤더: 제목 + 결재란 ========== */}
      <div className="flex justify-between items-start mb-4">
        <div>
          <h1 className="text-2xl font-bold tracking-widest mb-2">{title}</h1>
          <div className="text-[10px] space-y-1">
            <div className="flex gap-4">
              <span>문서번호: <strong>{data.shipmentNo}</strong></span>
              <span>작성일자: <strong>{data.scheduledDate}</strong></span>
            </div>
          </div>
        </div>
        <ConstructionApprovalTable approvers={{ writer: { name: data.registrant || '-' } }} />
      </div>

      {/* ========== 로트번호 / 제품명 / 제품코드 / 인정번호 ========== */}
      <table className="border border-gray-400 w-full mb-3 text-[10px]">
        <tbody>
          <tr>
            <td className="bg-gray-100 px-2 py-1 font-medium border-r border-gray-400 whitespace-nowrap">로트번호</td>
            <td className="px-2 py-1 border-r border-gray-400">{data.orderLotNo || data.lotNo}</td>
            <td className="bg-gray-100 px-2 py-1 font-medium border-r border-gray-400 whitespace-nowrap">제품명</td>
            <td className="px-2 py-1 border-r border-gray-400">{productRows[0]?.product_name || data.productGroups[0]?.productName || '-'}</td>
            <td className="bg-gray-100 px-2 py-1 font-medium border-r border-gray-400 whitespace-nowrap">제품코드</td>
            <td className="px-2 py-1 border-r border-gray-400">{productRows[0]?.product_code || '-'}</td>
            <td className="bg-gray-100 px-2 py-1 font-medium border-r border-gray-400 whitespace-nowrap">인정번호</td>
            <td className="px-2 py-1">{orderDetail?.category_code || '-'}</td>
          </tr>
        </tbody>
      </table>

      {/* ========== 3열 섹션: 신청업체 | 신청내용 | 납품정보 ========== */}
      <div className="border border-gray-400 mb-4">
        <div className="grid grid-cols-3">
          {/* 신청업체 */}
          <div className="border-r border-gray-400">
            <div className="bg-gray-200 text-center py-1 font-bold border-b border-gray-400">신청업체</div>
            <table className="w-full">
              <tbody>
                <tr className="border-b border-gray-300">
                  <td className="bg-gray-100 px-2 py-1 w-20 font-medium">수주일</td>
                  <td className="px-2 py-1">{orderDetail?.received_at || data.scheduledDate}</td>
                </tr>
                <tr className="border-b border-gray-300">
                  <td className="bg-gray-100 px-2 py-1 font-medium">수주처</td>
                  <td className="px-2 py-1">{data.customerName}</td>
                </tr>
                <tr className="border-b border-gray-300">
                  <td className="bg-gray-100 px-2 py-1 font-medium">수주 담당자</td>
                  <td className="px-2 py-1">{orderDetail?.manager_name || data.registrant || '-'}</td>
                </tr>
                <tr>
                  <td className="bg-gray-100 px-2 py-1 font-medium">담당자 연락처</td>
                  <td className="px-2 py-1">{orderDetail?.client_contact || data.driverContact || '-'}</td>
                </tr>
              </tbody>
            </table>
          </div>

          {/* 신청내용 */}
          <div className="border-r border-gray-400">
            <div className="bg-gray-200 text-center py-1 font-bold border-b border-gray-400">신청내용</div>
            <table className="w-full">
              <tbody>
                <tr className="border-b border-gray-300">
                  <td className="bg-gray-100 px-2 py-1 w-20 font-medium">현장명</td>
                  <td className="px-2 py-1">{data.siteName}</td>
                </tr>
                <tr className="border-b border-gray-300">
                  <td className="bg-gray-100 px-2 py-1 font-medium">납기요청일</td>
                  <td className="px-2 py-1">{orderDetail?.delivery_date || data.scheduledDate}</td>
                </tr>
                <tr className="border-b border-gray-300">
                  <td className="bg-gray-100 px-2 py-1 font-medium">출고일</td>
                  <td className="px-2 py-1">{data.shipmentDate || data.scheduledDate}</td>
                </tr>
                <tr>
                  <td className="bg-gray-100 px-2 py-1 font-medium">셔터출수량</td>
                  <td className="px-2 py-1">{shutterCount}개소</td>
                </tr>
              </tbody>
            </table>
          </div>

          {/* 납품정보 */}
          <div>
            <div className="bg-gray-200 text-center py-1 font-bold border-b border-gray-400">납품정보</div>
            <table className="w-full">
              <tbody>
                <tr className="border-b border-gray-300">
                  <td className="bg-gray-100 px-2 py-1 w-20 font-medium">현장명</td>
                  <td className="px-2 py-1">{data.siteName}</td>
                </tr>
                <tr className="border-b border-gray-300">
                  <td className="bg-gray-100 px-2 py-1 font-medium">인수담당자</td>
                  <td className="px-2 py-1">{data.receiver || '-'}</td>
                </tr>
                <tr className="border-b border-gray-300">
                  <td className="bg-gray-100 px-2 py-1 font-medium">인수자연락처</td>
                  <td className="px-2 py-1">{data.receiverContact || '-'}</td>
                </tr>
                <tr>
                  <td className="bg-gray-100 px-2 py-1 font-medium">배송방법</td>
                  <td className="px-2 py-1">{deliveryMethodLabel}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
        {/* 배송지 주소 - 한 줄 병합 */}
        <div className="border-t border-gray-400 flex">
          <div className="bg-gray-100 px-2 py-1 w-20 shrink-0 font-medium">배송지 주소</div>
          <div className="px-2 py-1 flex-1">{fullAddress}</div>
        </div>
      </div>

      {/* ========== 배차정보 (출고증에서만) ========== */}
      {showDispatchInfo && (() => {
        const dispatch = data.vehicleDispatches[0];
        return (
          <div className="border border-gray-400 mb-4">
            <div className="bg-gray-200 text-center py-1 font-bold border-b border-gray-400">배차정보</div>
            <table className="w-full">
              <tbody>
                <tr className="border-b border-gray-300">
                  <td className="bg-gray-100 px-1 py-1 w-[1%] font-medium border-r border-gray-300 whitespace-nowrap">물류업체</td>
                  <td className="px-2 py-1 border-r border-gray-300">{dispatch?.logisticsCompany || data.logisticsCompany || '-'}</td>
                  <td className="bg-gray-100 px-1 py-1 w-[1%] font-medium border-r border-gray-300 whitespace-nowrap">입차일시</td>
                  <td className="px-2 py-1" colSpan={3}>{dispatch?.arrivalDateTime || '-'}</td>
                </tr>
                <tr className="border-b border-gray-300">
                  <td className="bg-gray-100 px-1 py-1 w-[1%] font-medium border-r border-gray-300 whitespace-nowrap">톤수</td>
                  <td className="px-2 py-1 border-r border-gray-300">{dispatch?.tonnage || data.vehicleTonnage || '-'}</td>
                  <td className="bg-gray-100 px-1 py-1 w-[1%] font-medium border-r border-gray-300 whitespace-nowrap">차량번호</td>
                  <td className="px-2 py-1 border-r border-gray-300">{dispatch?.vehicleNo || data.vehicleNo || '-'}</td>
                  <td className="bg-gray-100 px-1 py-1 w-[1%] font-medium border-r border-gray-300 whitespace-nowrap">기사연락처</td>
                  <td className="px-2 py-1 whitespace-nowrap">{dispatch?.driverContact || data.driverContact || '-'}</td>
                </tr>
                <tr>
                  <td className="bg-gray-100 px-1 py-1 w-[1%] font-medium border-r border-gray-300 whitespace-nowrap">비고</td>
                  <td className="px-2 py-1" colSpan={5}>{dispatch?.remarks || '-'}</td>
                </tr>
              </tbody>
            </table>
          </div>
        );
      })()}

      <p className="text-[10px] mb-4">아래와 같이 주문하오니 품질 및 납기일을 준수하여 주시기 바랍니다.</p>

      {/* ========== 1. 스크린 ========== */}
      {screenProducts.length > 0 && (
        <div className="mb-4">
          <p className="font-bold mb-2">1. 스크린</p>
          <div className="border border-gray-400">
            <table className="w-full">
              <thead>
                <tr className="bg-gray-100 border-b border-gray-400">
                  <th className={`${thBase} w-8`} rowSpan={2}>No</th>
                  <th className={`${thBase} w-14`} rowSpan={2}>품류</th>
                  <th className={`${thBase} w-14`} rowSpan={2}>부호</th>
                  <th className={thBase} colSpan={2}>오픈사이즈</th>
                  <th className={thBase} colSpan={2}>제작사이즈</th>
                  <th className={`${thBase} w-16`} rowSpan={2}>가이드<br />레일</th>
                  <th className={`${thBase} w-14`} rowSpan={2}>사프트<br />(인치)</th>
                  <th className={`${thBase} w-14`} rowSpan={2}>케이스<br />(인치)</th>
                  <th className={thBase} colSpan={2}>모터</th>
                  <th className="px-1 py-1 w-16" rowSpan={2}>마감</th>
                </tr>
                <tr className="bg-gray-50 border-b border-gray-400 text-[9px]">
                  <th className={thBase}>가로</th>
                  <th className={thBase}>세로</th>
                  <th className={thBase}>가로</th>
                  <th className={thBase}>세로</th>
                  <th className={thBase}>브라켓트</th>
                  <th className={thBase}>용량Kg</th>
                </tr>
              </thead>
              <tbody>
                {screenProducts.map((row) => (
                  <tr key={row.no} className="border-b border-gray-300">
                    <td className={tdCenter}>{row.no}</td>
                    <td className={tdCenter}>{row.floor ?? '-'}</td>
                    <td className={tdCenter}>{row.symbol ?? '-'}</td>
                    <td className={tdCenter}>{row.open_width ? formatNumber(Number(row.open_width)) : '-'}</td>
                    <td className={tdCenter}>{row.open_height ? formatNumber(Number(row.open_height)) : '-'}</td>
                    <td className={tdCenter}>{row.made_width ? formatNumber(Number(row.made_width)) : '-'}</td>
                    <td className={tdCenter}>{row.made_height ? formatNumber(Number(row.made_height)) : '-'}</td>
                    <td className={tdCenter}>{row.guide_rail ?? '-'}</td>
                    <td className={tdCenter}>{row.shaft ?? '-'}</td>
                    <td className={tdCenter}>{row.case_inch ?? '-'}</td>
                    <td className={tdCenter}>{row.bracket ?? '-'}</td>
                    <td className={tdCenter}>{row.capacity ?? '-'}</td>
                    <td className="px-1 py-1 text-center">{row.finish ?? '-'}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* ========== 2. 철재 ========== */}
      {steelProducts.length > 0 && (
        <div className="mb-4">
          <p className="font-bold mb-2">2. 철재</p>
          <div className="border border-gray-400">
            <table className="w-full">
              <thead>
                <tr className="bg-gray-100 border-b border-gray-400">
                  <th className={`${thBase} w-8`} rowSpan={2}>No.</th>
                  <th className={`${thBase} w-14`} rowSpan={2}>부호</th>
                  <th className={thBase} colSpan={2}>오픈사이즈</th>
                  <th className={thBase} colSpan={2}>제작사이즈</th>
                  <th className={`${thBase} w-16`} rowSpan={2}>가이드<br />레일</th>
                  <th className={`${thBase} w-14`} rowSpan={2}>사프트<br />(인치)</th>
                  <th className={`${thBase} w-14`} rowSpan={2}>조인트바<br />(규격)</th>
                  <th className={`${thBase} w-14`} rowSpan={2}>케이스<br />(인치)</th>
                  <th className={thBase} colSpan={2}>모터</th>
                  <th className="px-1 py-1 w-16" rowSpan={2}>마감</th>
                </tr>
                <tr className="bg-gray-50 border-b border-gray-400 text-[9px]">
                  <th className={thBase}>가로</th>
                  <th className={thBase}>세로</th>
                  <th className={thBase}>가로</th>
                  <th className={thBase}>세로</th>
                  <th className={thBase}>브라켓트</th>
                  <th className={thBase}>용량Kg</th>
                </tr>
              </thead>
              <tbody>
                {steelProducts.map((row) => (
                  <tr key={row.no} className="border-b border-gray-300">
                    <td className={tdCenter}>{row.no}</td>
                    <td className={tdCenter}>{row.symbol ?? '-'}</td>
                    <td className={tdCenter}>{row.open_width ? formatNumber(Number(row.open_width)) : '-'}</td>
                    <td className={tdCenter}>{row.open_height ? formatNumber(Number(row.open_height)) : '-'}</td>
                    <td className={tdCenter}>{row.made_width ? formatNumber(Number(row.made_width)) : '-'}</td>
                    <td className={tdCenter}>{row.made_height ? formatNumber(Number(row.made_height)) : '-'}</td>
                    <td className={tdCenter}>{row.guide_rail ?? '-'}</td>
                    <td className={tdCenter}>{row.shaft ?? '-'}</td>
                    <td className={tdCenter}>{row.joint_bar ?? '-'}</td>
                    <td className={tdCenter}>{row.case_inch ?? '-'}</td>
                    <td className={tdCenter}>{row.bracket ?? '-'}</td>
                    <td className={tdCenter}>{row.capacity ?? '-'}</td>
                    <td className="px-1 py-1 text-center">{row.finish ?? '-'}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* ========== 3. 모터 ========== */}
      {motorRows > 0 && (
        <div className="mb-4">
          <p className="font-bold mb-2">3. 모터</p>
          <div className="border border-gray-400">
            <table className="w-full">
              <thead>
                <tr className="bg-gray-100 border-b border-gray-400">
                  <th className={`${thBase} w-20`}>항목</th>
                  <th className={`${thBase} w-20`}>구분</th>
                  <th className={`${thBase} w-20`}>규격</th>
                  <th className={`${thBase} w-10`}>수량</th>
                  {showLotColumn && <th className={`${thBase} w-16`}>입고 LOT</th>}
                  <th className={`${thBase} w-20`}>항목</th>
                  <th className={`${thBase} w-20`}>구분</th>
                  <th className={`${thBase} w-20`}>규격</th>
                  <th className={showLotColumn ? `${thBase} w-10` : 'px-1 py-1 w-10'}>수량</th>
                  {showLotColumn && <th className="px-1 py-1 w-16">입고 LOT</th>}
                </tr>
              </thead>
              <tbody>
                {Array.from({ length: motorRows }).map((_, i) => {
                  const left = motorsLeft[i];
                  const right = motorsRight[i];
                  return (
                    <tr key={i} className="border-b border-gray-300">
                      <td className={tdBase}>{left?.item || ''}</td>
                      <td className={tdBase}>{left?.type || ''}</td>
                      <td className={tdBase}>{left?.spec || ''}</td>
                      <td className={tdCenter}>{left?.qty ?? ''}</td>
                      {showLotColumn && <td className={tdCenter}>{left?.lot || ''}</td>}
                      <td className={tdBase}>{right?.item || ''}</td>
                      <td className={tdBase}>{right?.type || ''}</td>
                      <td className={tdBase}>{right?.spec || ''}</td>
                      <td className={showLotColumn ? tdCenter : 'px-1 py-1 text-center'}>{right?.qty ?? ''}</td>
                      {showLotColumn && <td className="px-1 py-1 text-center">{right?.lot || ''}</td>}
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* ========== 4. 절곡물 ========== */}
      {bendingParts.length > 0 && (
        <div className="mb-4">
          <p className="font-bold mb-2">4. 절곡물</p>

          {/* 4-1. 가이드레일 */}
          {guideRailItems.length > 0 && (
            <div className="mb-3">
              <p className="text-[10px] font-medium mb-1">4-1. 가이드레일</p>
              <div className="border border-gray-400">
                <table className="w-full">
                  <thead>
                    <tr className="bg-gray-100 border-b border-gray-400">
                      <th className={`${thBase} w-32`}>&nbsp;</th>
                      <th className={`${thBase} w-24`}>항목</th>
                      <th className={`${thBase} w-20`}>규격</th>
                      <th className="px-1 py-1 w-14">수량</th>
                    </tr>
                  </thead>
                  <tbody>
                    {guideRailItems.map((item, i) => (
                      <tr key={i} className="border-b border-gray-300">
                        {i === 0 && (
                          <td className={tdCenter} rowSpan={guideRailItems.length}>
                            <div className={`${imgPlaceholder} h-20 w-full`}>IMG</div>
                          </td>
                        )}
                        <td className={tdCenter}>{item.name}</td>
                        <td className={tdCenter}>{item.spec}</td>
                        <td className="px-1 py-1 text-center">{item.qty}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>

              {/* 가이드레일 연기차단재 */}
              {guideSmokeItems.length > 0 && (
                <div className="mt-1 border border-gray-400">
                  <table className="w-full">
                    <thead>
                      <tr className="bg-gray-50 border-b border-gray-400 text-[10px]">
                        <th className={`${thBase} w-32`}>&nbsp;</th>
                        <th className={`${thBase} w-24`}>항목</th>
                        <th className={`${thBase} w-20`}>규격</th>
                        <th className="px-1 py-1 w-14">수량</th>
                      </tr>
                    </thead>
                    <tbody>
                      {guideSmokeItems.map((item, i) => (
                        <tr key={i} className="border-b border-gray-300">
                          {i === 0 && (
                            <td className={tdCenter} rowSpan={guideSmokeItems.length}>
                              <div className={`${imgPlaceholder} h-14 w-full`}>IMG</div>
                            </td>
                          )}
                          <td className={tdCenter}>{item.name}</td>
                          <td className={tdCenter}>{item.spec}</td>
                          <td className="px-1 py-1 text-center">{item.qty}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}

              <p className="mt-1 text-[10px]">
                <span className="font-medium">* 가이드레일 마감재 <span className="text-red-600 font-bold">양측에</span> 설치</span> - EGI 0.8T + 화이버글라스코팅직물
              </p>
            </div>
          )}

          {/* 4-2. 케이스(셔터박스) */}
          {caseItems.length > 0 && (
            <div className="mb-3">
              <p className="text-[10px] font-medium mb-1">4-2. 케이스(셔터박스)</p>
              <div className="border border-gray-400">
                <table className="w-full">
                  <thead>
                    <tr className="bg-gray-100 border-b border-gray-400">
                      <th className={`${thBase} w-32`}>&nbsp;</th>
                      <th className={`${thBase} w-24`}>항목</th>
                      <th className={`${thBase} w-20`}>규격</th>
                      <th className="px-1 py-1 w-14">수량</th>
                    </tr>
                  </thead>
                  <tbody>
                    {caseItems.map((item, i) => (
                      <tr key={i} className="border-b border-gray-300">
                        {i === 0 && (
                          <td className={tdCenter} rowSpan={caseItems.length}>
                            <div className={`${imgPlaceholder} h-24 w-full`}>IMG</div>
                          </td>
                        )}
                        <td className={tdCenter}>{item.name}</td>
                        <td className={tdCenter}>{item.spec}</td>
                        <td className="px-1 py-1 text-center">{item.qty}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>

              {/* 케이스 연기차단재 */}
              {caseSmokeItems.length > 0 && (
                <div className="mt-1 border border-gray-400">
                  <table className="w-full">
                    <thead>
                      <tr className="bg-gray-50 border-b border-gray-400 text-[10px]">
                        <th className={`${thBase} w-32`}>&nbsp;</th>
                        <th className={`${thBase} w-24`}>항목</th>
                        <th className={`${thBase} w-20`}>규격</th>
                        <th className="px-1 py-1 w-14">수량</th>
                      </tr>
                    </thead>
                    <tbody>
                      {caseSmokeItems.map((item, i) => (
                        <tr key={i} className="border-b border-gray-300">
                          {i === 0 && (
                            <td className={tdCenter} rowSpan={caseSmokeItems.length}>
                              <div className={`${imgPlaceholder} h-14 w-full`}>IMG</div>
                            </td>
                          )}
                          <td className={tdCenter}>{item.name}</td>
                          <td className={tdCenter}>{item.spec}</td>
                          <td className="px-1 py-1 text-center">{item.qty}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}

              <p className="mt-1 text-[10px]">
                <span className="font-medium">* 전면부, 판넬부 <span className="text-red-600 font-bold">양측에</span> 설치</span> - EGI 0.8T + 화이버글라스코팅직물
              </p>
            </div>
          )}

          {/* 4-3. 하단마감재 */}
          {bottomItems.length > 0 && (
            <div className="mb-3">
              <p className="text-[10px] font-medium mb-1">4-3. 하단마감재</p>
              <div className="border border-gray-400">
                <table className="w-full">
                  <thead>
                    <tr className="bg-gray-100 border-b border-gray-400">
                      <th className={`${thBase} w-32`}>&nbsp;</th>
                      <th className={`${thBase} w-24`}>항목</th>
                      <th className={`${thBase} w-20`}>규격</th>
                      <th className="px-1 py-1 w-14">수량</th>
                    </tr>
                  </thead>
                  <tbody>
                    {bottomItems.map((item, i) => (
                      <tr key={i} className="border-b border-gray-300">
                        {i === 0 && (
                          <td className={tdCenter} rowSpan={bottomItems.length}>
                            <div className={`${imgPlaceholder} h-16 w-full`}>IMG</div>
                          </td>
                        )}
                        <td className={tdCenter}>{item.name}</td>
                        <td className={tdCenter}>{item.spec}</td>
                        <td className="px-1 py-1 text-center">{item.qty}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}

          {/* 연기차단재 (구분 불가) */}
          {otherSmokeItems.length > 0 && (
            <div className="mb-3">
              <p className="text-[10px] font-medium mb-1">연기차단재</p>
              <div className="border border-gray-400">
                <table className="w-full">
                  <thead>
                    <tr className="bg-gray-50 border-b border-gray-400 text-[10px]">
                      <th className={`${thBase} w-24`}>항목</th>
                      <th className={`${thBase} w-20`}>규격</th>
                      <th className="px-1 py-1 w-14">수량</th>
                    </tr>
                  </thead>
                  <tbody>
                    {otherSmokeItems.map((item, i) => (
                      <tr key={i} className="border-b border-gray-300">
                        <td className={tdCenter}>{item.name}</td>
                        <td className={tdCenter}>{item.spec}</td>
                        <td className="px-1 py-1 text-center">{item.qty}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}
        </div>
      )}

      {/* ========== 5. 부자재 ========== */}
      {subsidiaryParts.length > 0 && (
        <div className="mb-4">
          <p className="font-bold mb-2">5. 부자재</p>
          <div className="border border-gray-400">
            <table className="w-full">
              <thead>
                <tr className="bg-gray-100 border-b border-gray-400">
                  <th className={`${thBase} w-24`}>항목</th>
                  <th className={`${thBase} w-20`}>규격</th>
                  <th className={`${thBase} w-10`}>수량</th>
                  <th className={`${thBase} w-24`}>항목</th>
                  <th className={`${thBase} w-20`}>규격</th>
                  <th className="px-1 py-1 w-10">수량</th>
                </tr>
              </thead>
              <tbody>
                {subsidiaryRows.map((row, i) => (
                  <tr key={i} className="border-b border-gray-300">
                    <td className={tdBase}>{row.left?.name ?? ''}</td>
                    <td className={tdCenter}>{row.left?.spec ?? ''}</td>
                    <td className={tdCenter}>{row.left?.qty ?? ''}</td>
                    <td className={tdBase}>{row.right?.name ?? ''}</td>
                    <td className={tdCenter}>{row.right?.spec ?? ''}</td>
                    <td className="px-1 py-1 text-center">{row.right?.qty ?? ''}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* ========== 특이사항 ========== */}
      {data.remarks && (
        <div className="mb-4">
          <p className="font-bold mb-2">【 특이사항 】</p>
          <div className="border border-gray-400 p-3 min-h-[40px]">
            {data.remarks}
          </div>
        </div>
      )}
    </div>
  );
}