'use client';

/**
 * 절곡 중간검사 성적서 문서 콘텐츠
 *
 * 기획서 기준:
 * - 헤더: "중간검사성적서 (절곡)" + 결재란
 * - 기본정보: 제품명/슬랫, 규격/절곡, 수주처, 현장명 | 제품LOT NO, 로트크기, 검사일자, 검사자
 *   + 제품명/KWE01, 마감유형/소니자감
 * - ■ 중간검사 기준서: 2섹션 (가이드레일류 + 연기차단재)
 * - ■ 중간검사 DATA: 분류, 제품명, 타입, 절곡상태결모양(양호/불량),
 *   길이(도면치수/측정값입력), 너비(도면치수/측정값입력),
 *   간격(포인트/도면치수/측정값입력), 판정(자동)
 * - 부적합 내용 / 종합판정(자동)
 */

import { useState, useCallback, useMemo, forwardRef, useImperativeHandle, useEffect } from 'react';
import type { WorkOrder } from '../types';
import type { BendingInfoExtended } from './bending/types';
import type { InspectionData } from '@/components/production/WorkerScreen/InspectionInputModal';
import type { WorkItemData } from '@/components/production/WorkerScreen/types';
import type { InspectionDataMap } from './InspectionReportModal';
import type { InspectionSetting } from '@/types/process';
import {
  type CheckStatus,
  type InspectionContentRef,
  convertToCheckStatus,
  getFullDate,
  getToday,
  getOrderInfo,
  calculateOverallResult,
  INPUT_CLASS,
  InspectionCheckbox,
  JudgmentCell,
  InspectionLayout,
  InspectionFooter,
  InspectionStandardSection,
} from './inspection-shared';

export type { InspectionContentRef };

export interface BendingInspectionContentProps {
  data: WorkOrder;
  readOnly?: boolean;
  inspectionData?: InspectionData;
  workItems?: WorkItemData[];
  inspectionDataMap?: InspectionDataMap;
  inspectionSetting?: InspectionSetting;
  schematicImage?: string;
  inspectionStandardImage?: string;
}

interface GapPoint {
  point: string;
  designValue: string;
  measured: string;
}

interface ProductRow {
  id: string;
  category: string;
  productName: string;
  productType: string;
  bendingStatus: CheckStatus;
  lengthDesign: string;
  lengthMeasured: string;
  widthDesign: string;
  widthMeasured: string;
  gapPoints: GapPoint[];
}

/** 기본 gap 프로파일 (bendingInfo 없을 때 폴백) */
const DEFAULT_GAP_PROFILES = {
  wall: [
    { point: '①', designValue: '30' }, { point: '②', designValue: '80' },
    { point: '③', designValue: '45' }, { point: '④', designValue: '40' },
    { point: '⑤', designValue: '34' },
  ],
  side: [
    { point: '①', designValue: '28' }, { point: '②', designValue: '75' },
    { point: '③', designValue: '42' }, { point: '④', designValue: '38' },
    { point: '⑤', designValue: '32' },
  ],
  case: [
    { point: '①', designValue: '380' }, { point: '②', designValue: '50' },
    { point: '③', designValue: '240' }, { point: '④', designValue: '50' },
  ],
  bottomBar: [
    { point: '①', designValue: '60' }, { point: '②', designValue: '64' },
  ],
  lBar: [{ point: '①', designValue: '17' }],
  smokeW50: [{ point: '①', designValue: '50' }, { point: '②', designValue: '12' }],
  smokeW80: [{ point: '①', designValue: '80' }, { point: '②', designValue: '12' }],
};

type ProductTemplate = Omit<ProductRow, 'bendingStatus' | 'lengthMeasured' | 'widthMeasured'>;

/** bendingInfo 기반으로 검사 대상 부품 동적 생성 */
function buildProductsFromBendingInfo(bendingInfo?: BendingInfoExtended): ProductTemplate[] {
  if (!bendingInfo?.productCode) return [];
  const code = bendingInfo.productCode;
  const isStock = bendingInfo.isStockProduction;
  const stockKeys = new Set(bendingInfo.stockPartFilter?.map(f => f.partKey) || []);

  // 길이 추출 헬퍼
  const getLength = (data?: { lengthData?: Array<{ length: number }> }): string => {
    const len = data?.lengthData?.[0]?.length;
    return len ? String(len) : '3000';
  };

  const products: ProductTemplate[] = [];

  // 가이드레일 벽면
  const hasWall = bendingInfo?.guideRail?.wall;
  if (hasWall && (!isStock || stockKeys.size === 0)) {
    products.push({
      id: 'guide-rail-wall', category: code, productName: '가이드레일', productType: '벽면형',
      lengthDesign: getLength(hasWall), widthDesign: 'N/A',
      gapPoints: DEFAULT_GAP_PROFILES.wall.map(p => ({ ...p, measured: '' })),
    });
  }

  // 가이드레일 측면
  const hasSide = bendingInfo?.guideRail?.side;
  if (hasSide) {
    // STOCK 필터: 가이드레일 관련 부품이면 표시
    if (!isStock || stockKeys.size === 0 || ['본체', 'C형', 'D형', '마감재', '별도마감'].some(k => stockKeys.has(k))) {
      products.push({
        id: 'guide-rail-side', category: code, productName: '가이드레일', productType: '측면형',
        lengthDesign: getLength(hasSide), widthDesign: 'N/A',
        gapPoints: DEFAULT_GAP_PROFILES.side.map(p => ({ ...p, measured: '' })),
      });
    }
  }

  // 케이스
  if (bendingInfo?.shutterBox && bendingInfo.shutterBox.length > 0) {
    const box = bendingInfo.shutterBox[0];
    products.push({
      id: 'case', category: code, productName: '케이스', productType: box.size || '500X380',
      lengthDesign: getLength(box), widthDesign: 'N/A',
      gapPoints: DEFAULT_GAP_PROFILES.case.map(p => ({ ...p, measured: '' })),
    });
  } else if (!isStock) {
    products.push({
      id: 'case', category: code, productName: '케이스', productType: '500X380',
      lengthDesign: '3000', widthDesign: 'N/A',
      gapPoints: DEFAULT_GAP_PROFILES.case.map(p => ({ ...p, measured: '' })),
    });
  }

  // 하단마감재
  if (bendingInfo?.bottomBar) {
    const len = bendingInfo.bottomBar.length3000Qty > 0 ? '3000' : bendingInfo.bottomBar.length4000Qty > 0 ? '4000' : '3000';
    products.push({
      id: 'bottom-finish', category: code, productName: '하단마감재', productType: '60X40',
      lengthDesign: len, widthDesign: 'N/A',
      gapPoints: DEFAULT_GAP_PROFILES.bottomBar.map(p => ({ ...p, measured: '' })),
    });
    products.push({
      id: 'bottom-l-bar', category: code, productName: '하단L-BAR', productType: '17X60',
      lengthDesign: len, widthDesign: 'N/A',
      gapPoints: DEFAULT_GAP_PROFILES.lBar.map(p => ({ ...p, measured: '' })),
    });
  } else if (!isStock) {
    products.push({
      id: 'bottom-finish', category: code, productName: '하단마감재', productType: '60X40',
      lengthDesign: '3000', widthDesign: 'N/A',
      gapPoints: DEFAULT_GAP_PROFILES.bottomBar.map(p => ({ ...p, measured: '' })),
    });
    products.push({
      id: 'bottom-l-bar', category: code, productName: '하단L-BAR', productType: '17X60',
      lengthDesign: '3000', widthDesign: 'N/A',
      gapPoints: DEFAULT_GAP_PROFILES.lBar.map(p => ({ ...p, measured: '' })),
    });
  }

  // 연기차단재
  if (bendingInfo?.smokeBarrier) {
    const len = bendingInfo.smokeBarrier.w50?.[0]?.length ? String(bendingInfo.smokeBarrier.w50[0].length) : '3000';
    products.push({
      id: 'smoke-w50', category: code, productName: '연기차단재', productType: 'W50\n가이드레일용',
      lengthDesign: len, widthDesign: '',
      gapPoints: DEFAULT_GAP_PROFILES.smokeW50.map(p => ({ ...p, measured: '' })),
    });
    products.push({
      id: 'smoke-w80', category: code, productName: '연기차단재', productType: 'W80\n케이스용',
      lengthDesign: len, widthDesign: '',
      gapPoints: DEFAULT_GAP_PROFILES.smokeW80.map(p => ({ ...p, measured: '' })),
    });
  } else if (!isStock) {
    products.push({
      id: 'smoke-w50', category: code, productName: '연기차단재', productType: 'W50\n가이드레일용',
      lengthDesign: '3000', widthDesign: '',
      gapPoints: DEFAULT_GAP_PROFILES.smokeW50.map(p => ({ ...p, measured: '' })),
    });
    products.push({
      id: 'smoke-w80', category: code, productName: '연기차단재', productType: 'W80\n케이스용',
      lengthDesign: '3000', widthDesign: '',
      gapPoints: DEFAULT_GAP_PROFILES.smokeW80.map(p => ({ ...p, measured: '' })),
    });
  }

  return products;
}

export const BendingInspectionContent = forwardRef<InspectionContentRef, BendingInspectionContentProps>(function BendingInspectionContent({
  data: order,
  readOnly = false,
  workItems,
  inspectionDataMap,
  inspectionSetting,
  schematicImage: schematicImageProp,
}, ref) {
  const schematicImage = inspectionSetting?.schematicImage || schematicImageProp;
  const fullDate = getFullDate();
  const today = getToday();
  const { documentNo, primaryAssignee } = getOrderInfo(order);

  const bendingInfo = order.bendingInfo as BendingInfoExtended | undefined;
  const productCode = bendingInfo?.productCode || '-';
  const finishMaterial = bendingInfo?.finishMaterial || '-';

  const [products, setProducts] = useState<ProductRow[]>([]);
  const [inadequateContent, setInadequateContent] = useState('');

  // bendingInfo + 저장된 검사 데이터를 통합하여 products 생성
  useEffect(() => {
    // 1. bendingInfo 기반 templates 생성 (해당 부품만)
    const templates = buildProductsFromBendingInfo(bendingInfo);
    if (templates.length === 0) return;

    // 2. 저장된 검사 데이터 찾기
    let itemData: InspectionData | undefined;
    if (workItems && inspectionDataMap) {
      for (const item of workItems) {
        const data = inspectionDataMap.get(item.id);
        if (data) {
          itemData = data as unknown as InspectionData;
          break;
        }
      }
    }

    const savedProducts = (itemData as unknown as Record<string, unknown> | undefined)?.products as Array<{
      id: string;
      bendingStatus: CheckStatus;
      lengthMeasured: string;
      widthMeasured: string;
      gapPoints: Array<{ point: string; designValue: string; measured: string }>;
    }> | undefined;

    // 3. templates 기반으로 products 생성 + 저장 데이터 병합
    const newProducts: ProductRow[] = templates.map(p => {
      const saved = savedProducts?.find(sp => sp.id === p.id);
      const inferredStatus: CheckStatus = itemData?.bendingStatus
        ? convertToCheckStatus(itemData.bendingStatus)
        : itemData?.judgment === 'pass' ? '양호' : itemData?.judgment === 'fail' ? '불량' : null;

      return {
        ...p,
        bendingStatus: saved?.bendingStatus ?? inferredStatus ?? null,
        lengthMeasured: saved?.lengthMeasured || '',
        widthMeasured: saved?.widthMeasured || '',
        gapPoints: p.gapPoints.map((gp, gi) => ({
          ...gp,
          measured: saved?.gapPoints?.[gi]?.measured || '',
        })),
      };
    });

    setProducts(newProducts);

    // 부적합 내용 복원
    const savedInadequate = (itemData as unknown as Record<string, unknown> | undefined)?.inadequateContent;
    if (typeof savedInadequate === 'string' && savedInadequate) {
      setInadequateContent(savedInadequate);
    } else if (itemData?.nonConformingContent) {
      setInadequateContent(itemData.nonConformingContent);
    }
  }, [bendingInfo?.productCode, bendingInfo?.isStockProduction, workItems, inspectionDataMap]);

  const handleStatusChange = useCallback((productId: string, value: CheckStatus) => {
    if (readOnly) return;
    setProducts(prev => prev.map(p =>
      p.id === productId ? { ...p, bendingStatus: value } : p
    ));
  }, [readOnly]);

  const handleInputChange = useCallback((productId: string, field: 'lengthMeasured' | 'widthMeasured', value: string) => {
    if (readOnly) return;
    setProducts(prev => prev.map(p =>
      p.id === productId ? { ...p, [field]: value } : p
    ));
  }, [readOnly]);

  const handleGapMeasuredChange = useCallback((productId: string, gapIndex: number, value: string) => {
    if (readOnly) return;
    setProducts(prev => prev.map(p => {
      if (p.id !== productId) return p;
      const newGapPoints = p.gapPoints.map((gp, i) =>
        i === gapIndex ? { ...gp, measured: value } : gp
      );
      return { ...p, gapPoints: newGapPoints };
    }));
  }, [readOnly]);

  const getProductJudgment = useCallback((product: ProductRow): '적' | '부' | null => {
    if (product.bendingStatus === '불량') return '부';
    if (product.bendingStatus === '양호') return '적';
    return null;
  }, []);

  const overallResult = useMemo(() => calculateOverallResult(products.map(getProductJudgment)), [products, getProductJudgment]);

  useImperativeHandle(ref, () => ({
    getInspectionData: () => ({
      products: products.map(p => ({
        id: p.id,
        category: p.category,
        productName: p.productName,
        productType: p.productType,
        bendingStatus: p.bendingStatus,
        lengthMeasured: p.lengthMeasured,
        widthMeasured: p.widthMeasured,
        gapPoints: p.gapPoints.map(gp => ({
          point: gp.point,
          designValue: gp.designValue,
          measured: gp.measured,
        })),
      })),
      inadequateContent,
      overallResult,
    }),
  }), [products, inadequateContent, overallResult]);

  return (
    <InspectionLayout title="중간검사성적서 (절곡)" documentNo={documentNo} fullDate={fullDate} primaryAssignee={primaryAssignee}>
      {/* ===== 기본 정보 ===== */}
      <table className="w-full border-collapse text-xs mb-6">
        <tbody>
          <tr>
            <td className="border border-gray-400 bg-gray-50 px-3 py-2 font-medium w-24">제품명</td>
            <td className="border border-gray-400 px-3 py-2">{productCode}</td>
            <td className="border border-gray-400 bg-gray-50 px-3 py-2 font-medium w-28">제품 LOT NO</td>
            <td className="border border-gray-400 px-3 py-2">{order.lotNo || '-'}</td>
          </tr>
          <tr>
            <td className="border border-gray-400 bg-gray-50 px-3 py-2 font-medium">규격</td>
            <td className="border border-gray-400 px-3 py-2">절곡</td>
            <td className="border border-gray-400 bg-gray-50 px-3 py-2 font-medium">로트크기</td>
            <td className="border border-gray-400 px-3 py-2">{order.items?.length || 0} 개소</td>
          </tr>
          <tr>
            <td className="border border-gray-400 bg-gray-50 px-3 py-2 font-medium">수주처</td>
            <td className="border border-gray-400 px-3 py-2">{order.client || '-'}</td>
            <td className="border border-gray-400 bg-gray-50 px-3 py-2 font-medium">검사일자</td>
            <td className="border border-gray-400 px-3 py-2">{today}</td>
          </tr>
          <tr>
            <td className="border border-gray-400 bg-gray-50 px-3 py-2 font-medium">현장명</td>
            <td className="border border-gray-400 px-3 py-2">{order.projectName || '-'}</td>
            <td className="border border-gray-400 bg-gray-50 px-3 py-2 font-medium">검사자</td>
            <td className="border border-gray-400 px-3 py-2">{primaryAssignee}</td>
          </tr>
          <tr>
            <td className="border border-gray-400 bg-gray-50 px-3 py-2 font-medium">제품명</td>
            <td className="border border-gray-400 px-3 py-2">{productCode}</td>
            <td className="border border-gray-400 bg-gray-50 px-3 py-2 font-medium">마감유형</td>
            <td className="border border-gray-400 px-3 py-2">{finishMaterial || '-'}</td>
          </tr>
        </tbody>
      </table>

      {/* ===== 중간검사 기준서 ===== */}
      <InspectionStandardSection inspectionSetting={inspectionSetting}>
      <table className="w-full table-fixed border-collapse text-xs mb-4">
        <colgroup>
          <col style={{width: '80px'}} />
          <col style={{width: '180px'}} />
          <col style={{width: '58px'}} />
          <col style={{width: '58px'}} />
          <col />
          <col style={{width: '68px'}} />
          <col style={{width: '78px'}} />
          <col style={{width: '110px'}} />
        </colgroup>
        <tbody>
          <tr>
            <td className="border border-gray-400 px-2 py-1 font-bold text-center align-middle" rowSpan={6}>
              가이드레일<br/>케이스<br/>하단마감재<br/>하단 L-BAR
            </td>
            <td className="border border-gray-400 p-0" colSpan={7}>
              <div className="grid grid-cols-3 divide-x divide-gray-400">
                <div className="text-center font-medium bg-gray-100 py-1">가이드레일 도해</div>
                <div className="text-center font-medium bg-gray-100 py-1">케이스 도해</div>
                <div className="text-center font-medium bg-gray-100 py-1">하단마감재 도해</div>
              </div>
            </td>
          </tr>
          <tr>
            <td className="border border-gray-400 p-0" colSpan={7}>
              {schematicImage ? (
                <div className="h-28 flex items-center justify-center p-2">
                  <img src={schematicImage} alt="기준서 도해" className="max-h-24 mx-auto object-contain" />
                </div>
              ) : (
                <div className="grid grid-cols-3 divide-x divide-gray-400">
                  <div className="h-28 flex items-center justify-center text-gray-300 text-xs">IMG</div>
                  <div className="h-28 flex items-center justify-center text-gray-300 text-xs">IMG</div>
                  <div className="h-28 flex items-center justify-center text-gray-300 text-xs">IMG</div>
                </div>
              )}
            </td>
          </tr>
          <tr>
            <th className="border border-gray-400 bg-gray-100 px-2 py-1 text-center">도해</th>
            <th className="border border-gray-400 bg-gray-100 px-2 py-1 text-center" colSpan={2}>검사항목</th>
            <th className="border border-gray-400 bg-gray-100 px-2 py-1 text-center">검사기준</th>
            <th className="border border-gray-400 bg-gray-100 px-2 py-1 text-center">검사방법</th>
            <th className="border border-gray-400 bg-gray-100 px-2 py-1 text-center">검사주기</th>
            <th className="border border-gray-400 bg-gray-100 px-2 py-1 text-center">관련규정</th>
          </tr>
          <tr>
            <td className="border border-gray-400 p-2 text-center text-gray-500 align-middle text-xs" rowSpan={3}>
              절곡류 중간검사<br/>상세도면 참조
            </td>
            <td className="border border-gray-400 px-2 py-1 font-medium whitespace-nowrap">겉모양</td>
            <td className="border border-gray-400 px-2 py-1 font-medium whitespace-nowrap">절곡상태</td>
            <td className="border border-gray-400 px-2 py-1">사용상 해로운 결함이 없을것</td>
            <td className="border border-gray-400 px-2 py-1 text-center">육안검사</td>
            <td className="border border-gray-400 px-2 py-1 text-center" rowSpan={3}>n = 1, c = 0</td>
            <td className="border border-gray-400 px-2 py-1">KS F 4510 5.1항</td>
          </tr>
          <tr>
            <td className="border border-gray-400 px-2 py-1 font-medium bg-gray-50" rowSpan={2}>치수<br/>(mm)</td>
            <td className="border border-gray-400 px-2 py-1 font-medium">길이</td>
            <td className="border border-gray-400 px-2 py-1">도면치수 ± 4</td>
            <td className="border border-gray-400 px-2 py-1 text-center" rowSpan={2}>체크검사</td>
            <td className="border border-gray-400 px-2 py-1">KS F 4510 7항<br/>표9</td>
          </tr>
          <tr>
            <td className="border border-gray-400 px-2 py-1 font-medium">간격</td>
            <td className="border border-gray-400 px-2 py-1">도면치수 ± 2</td>
            <td className="border border-gray-400 px-2 py-1">KS F 4510 7항<br/>표9 / 자체규정</td>
          </tr>
        </tbody>
      </table>

      {/* ===== 중간검사 기준서 (2) 연기차단재 ===== */}
      <table className="w-full table-fixed border-collapse text-xs mb-6">
        <colgroup>
          <col style={{width: '80px'}} />
          <col style={{width: '180px'}} />
          <col style={{width: '52px'}} />
          <col style={{width: '52px'}} />
          <col />
          <col style={{width: '68px'}} />
          <col style={{width: '78px'}} />
          <col style={{width: '110px'}} />
        </colgroup>
        <tbody>
          <tr>
            <td className="border border-gray-400 px-2 py-1 font-bold text-center align-middle" rowSpan={6}>
              연기차단재
            </td>
            <th className="border border-gray-400 bg-gray-100 px-2 py-1 text-center">도해</th>
            <th className="border border-gray-400 bg-gray-100 px-2 py-1 text-center" colSpan={2}>검사항목</th>
            <th className="border border-gray-400 bg-gray-100 px-2 py-1 text-center">검사기준</th>
            <th className="border border-gray-400 bg-gray-100 px-2 py-1 text-center">검사방법</th>
            <th className="border border-gray-400 bg-gray-100 px-2 py-1 text-center">검사주기</th>
            <th className="border border-gray-400 bg-gray-100 px-2 py-1 text-center">관련규정</th>
          </tr>
          <tr>
            <td className="border border-gray-400 p-2 text-center align-middle" rowSpan={5}>
              <div className="h-32 flex items-center justify-center text-gray-300">도해 이미지 영역</div>
            </td>
            <td className="border border-gray-400 px-2 py-1 font-medium" rowSpan={2}>겉모양</td>
            <td className="border border-gray-400 px-2 py-1 font-medium" rowSpan={2}>절곡상태</td>
            <td className="border border-gray-400 px-2 py-1" rowSpan={2}>절단이 프레임에서 빠지지 않을것</td>
            <td className="border border-gray-400 px-2 py-1 text-center" rowSpan={2}>육안검사</td>
            <td className="border border-gray-400 px-2 py-1 text-center" rowSpan={5}>n = 1, c = 0</td>
            <td className="border border-gray-400 px-2 py-1">KS F 4510 5.1항</td>
          </tr>
          <tr>
            <td className="border border-gray-400 px-2 py-1">KS F 4510 7항<br/>표9 인용</td>
          </tr>
          <tr>
            <td className="border border-gray-400 px-2 py-1 font-medium bg-gray-50" rowSpan={3}>치수<br/>(mm)</td>
            <td className="border border-gray-400 px-2 py-1 font-medium">길이</td>
            <td className="border border-gray-400 px-2 py-1">도면치수 ± 4</td>
            <td className="border border-gray-400 px-2 py-1 text-center" rowSpan={3}>체크검사</td>
            <td className="border border-gray-400 px-2 py-1 text-center" rowSpan={3}>자체규정</td>
          </tr>
          <tr>
            <td className="border border-gray-400 px-2 py-1 font-medium">나비</td>
            <td className="border border-gray-400 px-2 py-1">W50 : 50 ± 5<br/>W80 : 80 ± 5</td>
          </tr>
          <tr>
            <td className="border border-gray-400 px-2 py-1 font-medium">간격</td>
            <td className="border border-gray-400 px-2 py-1">도면치수 ± 2</td>
          </tr>
        </tbody>
      </table>
      </InspectionStandardSection>

      {/* ===== 중간검사 DATA ===== */}
      <div className="mb-1 font-bold text-sm">■ 중간검사 DATA</div>
      <table className="w-full border-collapse text-xs mb-4">
        <thead>
          <tr className="bg-gray-100">
            <th className="border border-gray-400 p-1 w-14" rowSpan={2}>분류</th>
            <th className="border border-gray-400 p-1" rowSpan={2}>제품명</th>
            <th className="border border-gray-400 p-1 w-16" rowSpan={2}>타입</th>
            <th className="border border-gray-400 p-1 w-16" rowSpan={2}>절곡상태<br/>결모양</th>
            <th className="border border-gray-400 p-1" colSpan={2}>길이 (mm)</th>
            <th className="border border-gray-400 p-1" colSpan={2}>너비 (mm)</th>
            <th className="border border-gray-400 p-1" colSpan={3}>간격 (mm)</th>
            <th className="border border-gray-400 p-1 w-14" rowSpan={2}>판정<br/>(적/부)</th>
          </tr>
          <tr className="bg-gray-100">
            <th className="border border-gray-400 p-1 w-16">도면치수</th>
            <th className="border border-gray-400 p-1 w-16">측정값</th>
            <th className="border border-gray-400 p-1 w-16">도면치수</th>
            <th className="border border-gray-400 p-1 w-16">측정값</th>
            <th className="border border-gray-400 p-1 w-10">포인트</th>
            <th className="border border-gray-400 p-1 w-14">도면치수</th>
            <th className="border border-gray-400 p-1 w-14">측정값</th>
          </tr>
        </thead>
        <tbody>
          {products.map((product) => {
            const judgment = getProductJudgment(product);
            const rowCount = product.gapPoints.length;

            return product.gapPoints.map((gap, gapIdx) => (
              <tr key={`${product.id}-${gapIdx}`}>
                {gapIdx === 0 && (
                  <>
                    <td className="border border-gray-400 p-1 text-center font-medium bg-gray-50" rowSpan={rowCount}>{product.category}</td>
                    <td className="border border-gray-400 p-1" rowSpan={rowCount}>{product.productName}</td>
                    <td className="border border-gray-400 p-1 text-center whitespace-pre-line" rowSpan={rowCount}>{product.productType}</td>
                    <td className="border border-gray-400 p-1" rowSpan={rowCount}>
                      <div className="flex flex-col items-center gap-0.5">
                        <label className="flex items-center gap-0.5 cursor-pointer text-xs whitespace-nowrap">
                          <InspectionCheckbox
                            checked={product.bendingStatus === '양호'}
                            onClick={() => handleStatusChange(product.id, product.bendingStatus === '양호' ? null : '양호')}
                            readOnly={readOnly}
                          />
                          양호
                        </label>
                        <label className="flex items-center gap-0.5 cursor-pointer text-xs whitespace-nowrap">
                          <InspectionCheckbox
                            checked={product.bendingStatus === '불량'}
                            onClick={() => handleStatusChange(product.id, product.bendingStatus === '불량' ? null : '불량')}
                            readOnly={readOnly}
                          />
                          불량
                        </label>
                      </div>
                    </td>
                    <td className="border border-gray-400 p-1 text-center" rowSpan={rowCount}>{product.lengthDesign}</td>
                    <td className="border border-gray-400 p-1" rowSpan={rowCount}>
                      <input type="text" value={product.lengthMeasured} onChange={(e) => handleInputChange(product.id, 'lengthMeasured', e.target.value)} disabled={readOnly} className={INPUT_CLASS} placeholder="-" />
                    </td>
                    <td className="border border-gray-400 p-1 text-center" rowSpan={rowCount}>{product.widthDesign || 'N/A'}</td>
                    <td className="border border-gray-400 p-1" rowSpan={rowCount}>
                      <input type="text" value={product.widthMeasured} onChange={(e) => handleInputChange(product.id, 'widthMeasured', e.target.value)} disabled={readOnly} className={INPUT_CLASS} placeholder="-" />
                    </td>
                  </>
                )}
                <td className="border border-gray-400 p-1 text-center">{gap.point}</td>
                <td className="border border-gray-400 p-1 text-center">{gap.designValue}</td>
                <td className="border border-gray-400 p-1">
                  <input type="text" value={gap.measured} onChange={(e) => handleGapMeasuredChange(product.id, gapIdx, e.target.value)} disabled={readOnly} className={INPUT_CLASS} placeholder="-" />
                </td>
                {gapIdx === 0 && (
                  <JudgmentCell judgment={judgment} rowSpan={rowCount} />
                )}
              </tr>
            ));
          })}
        </tbody>
      </table>

      {/* ===== 부적합 내용 + 종합판정 ===== */}
      <InspectionFooter
        readOnly={readOnly}
        overallResult={overallResult}
        inadequateContent={inadequateContent}
        onInadequateContentChange={setInadequateContent}
      />
    </InspectionLayout>
  );
});
