// Vendor PWA cabinet schematic — read-only viewer that opens in a
// modal when the vendor clicks "View Schematic" on a cabinet card in
// the order detail page. The cut list is gated by the order's
// `showCutListToVendor` flag (admins toggle this per-order).
//
// This file ports the rules-engine math from the admin-portal's
// TypeScript implementation. It is intentionally kept in sync with
// `admin-portal/src/lib/cabinetSchematic/rulesEngine.ts` — when you
// change one, mirror the change here.

const { useState: useStCab, useEffect: useEfCab, useMemo: useMeCab } = React;

const INDUSTRY_DEFAULT_SC = {
  dadoDepth: 0.375, dadoSetback: 0.5, pocketScrewClearance: 0,
  confirmatEdgeOffset: 0.375, confirmatScrewSpacing: 4,
  scribeAllowance: 0.25, finishedSideOverhang: 0.25,
  faceFrameStileWidth: 1.5, faceFrameRailWidth: 1.5, faceFrameThickness: 0.75,
  toeKickHeight: 4.5, toeKickSetback: 3, toeKickThickness: 0.75,
  drawerSlideClearancePerSide: 0.5, shelfSetbackFromFace: 0.25, topStretcherWidth: 4,
  backPanelArea864ThresholdSqIn: 864, defaultBackThickness: 0.25, defaultBoxThickness: 0.75,
  sheetGoodWidth: 48, sheetGoodHeight: 96,
};

function fmtIn(v) {
  if (v == null || isNaN(v)) return '0"';
  const whole = Math.floor(v);
  const frac = v - whole;
  const sixteenths = Math.round(frac * 16);
  if (sixteenths === 0) return whole + '"';
  if (sixteenths === 16) return (whole + 1) + '"';
  const gcdf = (a, b) => (b === 0 ? a : gcdf(b, a % b));
  const g = gcdf(sixteenths, 16);
  const num = sixteenths / g;
  const den = 16 / g;
  return whole > 0 ? whole + '-' + num + '/' + den + '"' : num + '/' + den + '"';
}

function joineryOffset(joinery, sc) {
  if (joinery === 'dado') return 2 * sc.dadoDepth;
  return 0;
}

function pickBackThickness(w, h, sc, override) {
  if (override != null) return override;
  return (w * h) > sc.backPanelArea864ThresholdSqIn ? 0.5 : sc.defaultBackThickness;
}

// Simplified standard rules — matches admin computeStandard() output
function computeCabinetPanels(input, sc) {
  const boxT = input.boxThickness || sc.defaultBoxThickness;
  const backT = pickBackThickness(input.w, input.h, sc, input.backThickness);
  const joinery = input.joinery || 'confirmat';
  const off = joineryOffset(joinery, sc);
  const sideDepth = input.d;

  const panels = [];
  panels.push({ name: 'Side panel (×2)', qty: 2, w: sideDepth, h: input.h, t: boxT, joinery });

  const bottomW = (input.w - 2 * boxT) + off;
  panels.push({ name: 'Bottom', qty: 1, w: bottomW, h: sideDepth - sc.faceFrameThickness, t: boxT, joinery });

  const stretcherW = (input.w - 2 * boxT) + off;
  panels.push({ name: 'Top stretcher (front)', qty: 1, w: stretcherW, h: sc.topStretcherWidth, t: boxT, joinery });
  panels.push({ name: 'Top stretcher (back)', qty: 1, w: stretcherW, h: sc.topStretcherWidth, t: boxT, joinery });

  const backH = input.h + (joinery === 'dado' ? off : 0);
  panels.push({ name: 'Back panel', qty: 1, w: stretcherW, h: backH, t: backT, joinery });

  if (input.hasToeKick) {
    panels.push({ name: 'Toe kick', qty: 1, w: input.w - 2 * boxT, h: sc.toeKickHeight, t: sc.toeKickThickness, joinery: 'pocketScrew' });
  }
  if (input.shelves > 0) {
    panels.push({ name: 'Adjustable shelf', qty: input.shelves, w: input.w - 2 * boxT - 0.0625, h: input.d - sc.faceFrameThickness - sc.shelfSetbackFromFace, t: boxT, joinery: 'pocketScrew' });
  }
  if (input.drawers > 0) {
    panels.push({ name: 'Drawer box', qty: input.drawers, w: input.w - 2 * boxT - 2 * sc.drawerSlideClearancePerSide, h: 4, t: 0.5, joinery: 'pocketScrew' });
  }
  return panels;
}

function CabinetSchematicVendor({ cab, idx, showCutList }) {
  const [open, setOpen] = useStCab(false);
  const [view, setView] = useStCab('front');
  const [sc, setSc] = useStCab(INDUSTRY_DEFAULT_SC);

  useEfCab(() => {
    if (!open || !window.db) return;
    db.doc('shopConstants/current').get().then((snap) => {
      if (snap.exists) setSc({ ...INDUSTRY_DEFAULT_SC, ...snap.data() });
    }).catch(() => {});
  }, [open]);

  const w = parseFloat(cab.w) || 0;
  const h = parseFloat(cab.h) || 0;
  const d = parseFloat(cab.d) || 0;
  const doors = parseInt(cab.doors) || 0;
  const drawers = parseInt(cab.drawers) || 0;
  const shelves = parseInt(cab.shelves) || 0;
  const hasToeKick = h < 60 && d > 16; // base / drawer base / sink base

  const panels = useMeCab(() => {
    if (!w || !h || !d) return [];
    return computeCabinetPanels({ w, h, d, doors, drawers, shelves, hasToeKick }, sc);
  }, [w, h, d, doors, drawers, shelves, hasToeKick, sc]);

  if (!w || !h || !d) return null;

  return (
    <>
      <button className="btn ghost sm" onClick={() => setOpen(true)} style={{ marginTop: 6 }}>
        View Schematic
      </button>
      {open && (
        <div className="schematic-overlay" onClick={() => setOpen(false)}>
          <div className="schematic-modal" onClick={(e) => e.stopPropagation()}>
            <div className="schematic-head">
              <div>
                <div className="eyebrow">Cab {String(idx + 1).padStart(2, '0')}{cab.name ? ' — ' + cab.name : ''}</div>
                <h3>{w}" × {h}" × {d}"</h3>
              </div>
              <button className="schematic-close" onClick={() => setOpen(false)}>×</button>
            </div>
            <div className="schematic-tabs">
              {['front', 'back', 'left', 'right', 'top'].map((v) => (
                <button key={v} className={'schematic-tab' + (view === v ? ' on' : '')} onClick={() => setView(v)}>
                  {v.charAt(0).toUpperCase() + v.slice(1)}
                </button>
              ))}
            </div>
            <div className="schematic-body">
              <SchematicSvgVendor view={view} w={w} h={h} d={d} boxT={sc.defaultBoxThickness} hasToeKick={hasToeKick} sc={sc} />
              {showCutList ? (
                <div className="schematic-cutlist">
                  <h4>Cut List</h4>
                  <table>
                    <thead>
                      <tr>
                        <th>Panel</th>
                        <th style={{ textAlign: 'right' }}>Qty</th>
                        <th style={{ textAlign: 'right' }}>W</th>
                        <th style={{ textAlign: 'right' }}>H</th>
                        <th style={{ textAlign: 'right' }}>Thick</th>
                      </tr>
                    </thead>
                    <tbody>
                      {panels.map((p, i) => (
                        <tr key={i}>
                          <td>{p.name}</td>
                          <td style={{ textAlign: 'right' }} className="mono">{p.qty}</td>
                          <td style={{ textAlign: 'right' }} className="mono">{fmtIn(p.w)}</td>
                          <td style={{ textAlign: 'right' }} className="mono">{fmtIn(p.h)}</td>
                          <td style={{ textAlign: 'right' }} className="mono">{fmtIn(p.t)}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              ) : (
                <div className="schematic-cutlist-hidden">
                  Cut list is hidden for this order. Contact Precision Cabinets if you need it.
                </div>
              )}
            </div>
          </div>
        </div>
      )}
    </>
  );
}

function SchematicSvgVendor({ view, w, h, d, boxT, hasToeKick, sc }) {
  const outerW = view === 'left' || view === 'right' ? d : w;
  const outerH = view === 'top' ? d : h;
  const padding = 50;
  const targetMax = 360;
  const scale = Math.min(targetMax / outerW, targetMax / outerH);
  const dW = outerW * scale;
  const dH = outerH * scale;
  const total = padding * 2;

  return (
    <svg viewBox={`0 0 ${dW + total} ${dH + total}`} width="100%" style={{ maxHeight: 360 }}>
      <rect x={padding} y={padding} width={dW} height={dH} fill="#fef3c7" stroke="#b45309" strokeWidth={2} />
      {(view === 'front' || view === 'back') && (
        <>
          <rect x={padding} y={padding} width={boxT * scale} height={dH} fill="#fde68a" stroke="#b45309" />
          <rect x={padding + dW - boxT * scale} y={padding} width={boxT * scale} height={dH} fill="#fde68a" stroke="#b45309" />
        </>
      )}
      {hasToeKick && (view === 'front' || view === 'back') && (
        <rect
          x={padding + boxT * scale}
          y={padding + dH - sc.toeKickHeight * scale}
          width={dW - 2 * boxT * scale}
          height={sc.toeKickHeight * scale}
          fill="#92400e" opacity={0.3} stroke="#92400e"
        />
      )}
      {/* Top dimension */}
      <line x1={padding} y1={padding - 14} x2={padding + dW} y2={padding - 14} stroke="#92400e" strokeWidth={0.75} />
      <text x={padding + dW / 2} y={padding - 18} textAnchor="middle" fill="#92400e" fontSize={10}>{fmtIn(outerW)}</text>
      {/* Left dimension */}
      <text
        x={padding - 24} y={padding + dH / 2}
        textAnchor="middle" fill="#92400e" fontSize={10}
        transform={`rotate(-90 ${padding - 24} ${padding + dH / 2})`}
      >{fmtIn(outerH)}</text>
      <text x={(dW + total) / 2} y={dH + total - 8} textAnchor="middle" fill="#92400e" fontSize={11} fontWeight={600}>{view.toUpperCase()} VIEW</text>
    </svg>
  );
}

Object.assign(window, { CabinetSchematicVendor });
