// tc-kit.jsx — Cast & Crew "Box Rental Form" filler.
// Portrait 612x792, NO page rotation. We render the real PDF page to a canvas once
// (cached) for the on-screen preview, and overlay positioned values — same pattern
// as the time card. The PDF output overlays on the real uploaded PDF (pdf-gen.jsx).
//
// ▸ ALL placement lives in KIT_COORDS. x = right, y = down from TOP (baseline).
//   maxW = box width (text auto-shrinks). Edit one number to nudge a value.

const KIT_FORM = { w: 612, h: 792, src: 'uploads/' + encodeURIComponent('KIT RENTAL FORM.pdf') };

const KIT_COORDS = {
  company:     { x: 192, y: 128, size: 11, maxW: 340 },
  name:        { x: 122, y: 152, size: 11, maxW: 258 },
  ssn:         { x: 489, y: 152, size: 11, maxW: 55 },
  rentalRate:  { x: 158, y: 224, size: 11, maxW: 210 },
  weekEnding:  { x: 172, y: 297, size: 11, maxW: 165 },
  date:        { x: 305, y: 687, size: 11, maxW: 150 },
  // checkboxes: cx/cy = the CENTER of the printed box; the glyph is centered there.
  perDay:      { cx: 388, cy: 223, size: 9, isCheck: true },
  perWeek:     { cx: 434, cy: 223, size: 9, isCheck: true },
  invOnFile:   { cx: 187, cy: 494, size: 10, isCheck: true },
  invAttached: { cx: 245, cy: 494, size: 10, isCheck: true },
  // signature image sits ON the line, left portion
  signature:   { x: 80, y: 689, maxW: 195, maxH: 30, isImage: true },
};

// 8 inventory lines (baselines, top-down) — sit ~2.5pt above each printed rule
const KIT_INV_LINES = { x: 76, ys: [346, 364, 382, 400, 418, 436, 454, 472], size: 10.5, maxW: 462 };

// The uploaded blank form has a signature PRE-PRINTED above the Employee Signature
// line (scribble measured at x85–150, y663–687; line at y690). We paint white over
// it on every render so the form starts clean and only OUR signature shows.
const KIT_WHITEOUT = [
  { x: 74, y: 656, w: 150, h: 33 },
];

const KIT_FILL = '#15315e';

// Split inventory text into up to 8 visual lines (respects manual newlines, then wraps).
function kitInventoryLines(text) {
  if (!text) return [];
  const raw = String(text).split('\n');
  return raw.slice(0, KIT_INV_LINES.ys.length).map(s => s.trim());
}

function buildKitDrawOps({ profile, kit }) {
  const ops = [];
  const push = (key, text) => {
    if (text == null || text === '') return;
    const c = KIT_COORDS[key];
    ops.push({ x: c.x, y: c.y, size: c.size, align: 'left', text: String(text), maxW: c.maxW });
  };
  push('company', kit.company);
  push('name', profile.fullName);
  push('ssn', profile.ssnLast4);
  if (kit.rentalRate !== '' && kit.rentalRate != null) push('rentalRate', fmtMoney(parseFloat(kit.rentalRate)) || kit.rentalRate);
  const weDate = parseWeekEnding(kit.weekEnding);
  if (weDate) push('weekEnding', fmtDateMMDDYY(weDate));
  const dDate = isoToDate(kit.date);
  if (dDate) push('date', fmtDateMMDDYY(dDate));

  // checkmarks
  const checks = [];
  if (kit.rentalPer === 'day') checks.push('perDay');
  if (kit.rentalPer === 'week') checks.push('perWeek');
  if (kit.invCheck === 'onfile') checks.push('invOnFile');
  if (kit.invCheck === 'attached') checks.push('invAttached');
  for (const key of checks) {
    const c = KIT_COORDS[key];
    // emit box-center + size; renderers center the X glyph on (cx, cy)
    ops.push({ cx: c.cx, cy: c.cy, size: c.size || 9, text: 'X', isCheck: true });
  }

  // inventory lines
  kitInventoryLines(kit.inventory).forEach((line, i) => {
    if (!line) return;
    ops.push({ x: KIT_INV_LINES.x, y: KIT_INV_LINES.ys[i], size: KIT_INV_LINES.size, align: 'left', text: line, maxW: KIT_INV_LINES.maxW });
  });

  return ops;
}

// ── live background render (cached) ───────────────────────────────────────────
let _kitBgPromise = null;
function kitBackgroundDataURL() {
  if (_kitBgPromise) return _kitBgPromise;
  _kitBgPromise = (async () => {
    const pl = await window.__pdfjsReady;
    const pdf = await pl.getDocument({ url: KIT_FORM.src, isEvalSupported: false }).promise;
    const page = await pdf.getPage(1);
    const vp = page.getViewport({ scale: 2.4 });
    const c = document.createElement('canvas');
    c.width = vp.width; c.height = vp.height;
    await page.render({ canvasContext: c.getContext('2d'), viewport: vp, intent: 'print', annotationMode: 0 }).promise;
    return c.toDataURL('image/png');
  })();
  return _kitBgPromise;
}

const { useState: useKS, useEffect: useKE } = React;

function KitFormOverlay({ profile, kit, annotateMode, onAnnotations, uiScale }) {
  const [bg, setBg] = useKS(null);
  useKE(() => { let on = true; kitBackgroundDataURL().then(u => { if (on) setBg(u); }); return () => { on = false; }; }, []);

  const ops = buildKitDrawOps({ profile, kit });
  const sig = KIT_COORDS.signature;

  return (
    <div className="form-overlay kit-overlay" style={{ width: KIT_FORM.w + 'px', height: KIT_FORM.h + 'px' }}>
      {bg
        ? <img className="form-bg" src={bg} alt="Box Rental Form" draggable={false} />
        : <div className="form-bg form-bg-loading">Loading form…</div>}
      {KIT_WHITEOUT.map((r, i) => (
        <div key={'wo' + i} className="form-whiteout"
          style={{ left: r.x + 'px', top: r.y + 'px', width: r.w + 'px', height: r.h + 'px' }} />
      ))}
      {ops.map((op, i) => {
        if (op.isCheck) {
          // center the X glyph exactly on the printed box center
          const style = {
            left: op.cx + 'px', top: op.cy + 'px', fontSize: op.size + 'px',
            color: KIT_FILL, fontWeight: 700, lineHeight: 1,
            transform: 'translate(-50%, -50%)',
          };
          return <span key={i} className="fv fv-check" style={style}>{op.text}</span>;
        }
        const size = fitSize(op.text, op.size, op.maxW);
        const top = op.y - size * 0.80;
        const style = {
          left: op.x + 'px', top: top + 'px', fontSize: size + 'px', color: KIT_FILL,
          fontWeight: 400,
          transform: op.align === 'center' ? 'translateX(-50%)' : 'none',
        };
        return <span key={i} className="fv" style={style}>{op.text}</span>;
      })}
      {profile.signature && (
        <img className="form-sig" src={profile.signature} alt="signature"
          style={{ left: sig.x + 'px', top: (sig.y - sig.maxH) + 'px', maxWidth: sig.maxW + 'px', maxHeight: sig.maxH + 'px' }} />
      )}
      <AnnotationLayer formW={KIT_FORM.w} formH={KIT_FORM.h} ink={KIT_FILL} uiScale={uiScale}
        items={kit.annotations || []} active={!!annotateMode}
        onChange={(items) => onAnnotations && onAnnotations(items)} />
    </div>
  );
}

Object.assign(window, { KIT_FORM, KIT_COORDS, KIT_INV_LINES, KIT_WHITEOUT, KIT_FILL, buildKitDrawOps, kitInventoryLines, KitFormOverlay, kitBackgroundDataURL });
