// tc-form.jsx — THE single source of truth for field placement.
// Coordinates are in the form's LANDSCAPE space: 792 x 612 points,
// origin TOP-LEFT, y down. These numbers drive BOTH the on-screen overlay
// AND the pdf-lib overlay, so screen and PDF match the real template.
//
// ▸ Edit ONE number to nudge a value.  x = right, y = down.
// ▸ y is the TEXT BASELINE.  maxW = box width (text auto-shrinks to fit).
//
// We ONLY fill the fields below — everything else is payroll's to complete.

const FORM = { w: 792, h: 612, img: 'assets/form.png' };

const FIELD_COORDS = {
  projectTitle:  { x: 22,  y: 142, size: 15, maxW: 258, center: true },
  weekEnding:    { x: 509, y: 145, size: 12, maxW: 124, center: true },
  workState:     { x: 640, y: 145, size: 12, maxW: 69, center: true },   // box 636–713
  workCity:      { x: 718, y: 145, size: 11, maxW: 47, center: true },   // box 714–769

  employeeName:  { x: 22,  y: 176, size: 15, maxW: 258, center: true },
  ssnLast4:      { x: 350, y: 177, size: 13 },          // after preprinted "XXX-XX-"

  occupation:    { x: 414, y: 210, size: 14, maxW: 210, center: true },   // cell spans ~404–635, center ~519

  perDiemTotal:  { x: 30,  y: 547, size: 12, maxW: 95 },   // PD1 box, after preprinted "$"
  boxRental:     { x: 708, y: 527, size: 11, maxW: 55 },   // NO WITHHOLDING / 1099 (EQR), after "$"

  signature:     { x: 168, y: 583, maxW: 205, maxH: 32, isImage: true },   // right of printed "EMPLOYEE SIGN-"
};

// Time grid: rowY = baseline of each day row (S M T W T F S = Sun..Sat).
const GRID = {
  rowY: [259, 289, 318, 348, 378, 408, 437],
  size: 9,
  cols: {
    state:    { x: 32,  w: 30 },
    city:     { x: 61,  w: 22 },
    date:     { x: 88,  w: 28 },
    call:     { x: 124, w: 21 },
    mealOut1: { x: 150, w: 25 },
    mealIn1:  { x: 176, w: 25 },
    wrap:     { x: 271, w: 25 },
    note:     { x: 305, w: 38 },   // unlabeled box just right of WRAP
  },
  travelCenter: 199,
  travelMaxW: 165,
};

const FILL_COLOR = '#15315e';

function buildDrawOps({ profile, card, parsed, weekRows }) {
  const ops = [];
  const push = (key, text) => {
    if (text == null || text === '') return;
    const c = FIELD_COORDS[key];
    if (c.center) {
      ops.push({ x: c.x + c.maxW / 2, y: c.y, size: c.size, align: 'center', text: String(text), maxW: c.maxW });
    } else {
      ops.push({ x: c.x, y: c.y, size: c.size, align: 'left', text: String(text), maxW: c.maxW });
    }
  };

  const workState = card ? card.workState : '';
  const workCity = card ? card.workCity : '';

  push('projectTitle', card.projectTitle);
  push('weekEnding', parsed.weekEndingStr);
  push('workState', workState);
  push('workCity', workCity);
  push('employeeName', profile.fullName);
  push('ssnLast4', profile.ssnLast4);
  push('occupation', profile.occupation);

  const rate = card.perDiemRate !== '' && card.perDiemRate != null ? card.perDiemRate : profile.perDiemRate;
  const days = effectivePerDiemDays(card, parsed);
  if (days > 0 && (parseFloat(rate) || 0) > 0) push('perDiemTotal', fmtMoney(perDiemTotal(rate, days)));

  if (card.boxRental !== '' && card.boxRental != null && parseFloat(card.boxRental) > 0) {
    push('boxRental', fmtMoney(parseFloat(card.boxRental)));
  }

  weekRows.forEach((row, i) => {
    const d = row.day;
    if (!d) return;
    const y = GRID.rowY[i];
    const cell = (col, text) => {
      if (text == null || text === '') return;
      ops.push({ x: col.x, y, size: GRID.size, align: 'center', text: String(text), maxW: col.w });
    };
    cell(GRID.cols.date, d.mmdd);
    if (d.type === 'work') {
      cell(GRID.cols.call, d.call);
      cell(GRID.cols.mealOut1, d.mealOut);
      cell(GRID.cols.mealIn1, d.mealIn);
      cell(GRID.cols.wrap, d.wrap);
      cell(GRID.cols.note, d.note);
    } else if (d.type === 'travel') {
      cell(GRID.cols.note, d.note);
      const label = 'TRAVEL' + (d.span ? '  \u00B7  ' + d.span : '');
      ops.push({ x: GRID.travelCenter, y, size: GRID.size, align: 'center', text: label, maxW: GRID.travelMaxW, track: true, bg: true });
    } else if (d.type === 'status') {
      ops.push({ x: GRID.travelCenter, y, size: GRID.size, align: 'center', text: (d.statusText || ''), maxW: GRID.travelMaxW, track: true, bg: true });
    }
  });

  return ops;
}

// ── width measuring + auto-shrink (HTML side) ────────────────────────────────
let _measCtx = null;
function _measure(text, size) {
  if (!_measCtx) _measCtx = document.createElement('canvas').getContext('2d');
  const ff = (getComputedStyle(document.documentElement).getPropertyValue('--form-font') || '').trim()
    || "'Helvetica Neue', Helvetica, Arial, sans-serif";
  _measCtx.font = `500 ${size}px ${ff}`;
  return _measCtx.measureText(text).width;
}
function fitSize(text, size, maxW) {
  if (!maxW) return size;
  let s = size;
  while (s > 5 && _measure(text, s) > maxW) s -= 0.5;
  return s;
}

function FormOverlay({ profile, card, parsed, weekRows, annotateMode, onAnnotations, uiScale }) {
  const ops = buildDrawOps({ profile, card, parsed, weekRows });
  const sig = FIELD_COORDS.signature;
  return (
    <div className="form-overlay" style={{ width: FORM.w + 'px', height: FORM.h + 'px' }}>
      <img className="form-bg" src={FORM.img} alt="BTL Crew Time Card" draggable={false} />
      {ops.map((op, i) => {
        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: FILL_COLOR,
          letterSpacing: op.track ? '0.1em' : 'normal',
          transform: op.align === 'center' ? 'translateX(-50%)' : 'none',
        };
        if (op.bg) { style.background = '#fff'; style.padding = '0 3px'; }
        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={FORM.w} formH={FORM.h} ink={FILL_COLOR} uiScale={uiScale}
        items={card.annotations || []} active={!!annotateMode}
        onChange={(items) => onAnnotations && onAnnotations(items)} />
    </div>
  );
}

Object.assign(window, { FORM, FIELD_COORDS, GRID, FILL_COLOR, buildDrawOps, FormOverlay, fitSize });
