// tc-kitpanels.jsx — Box Rental Form editor + saved kit forms list.
const { useRef: useRefKP } = React;

function isoToDateKP(iso) { if (!iso) return null; const m = iso.match(/^(\d{4})-(\d{1,2})-(\d{1,2})$/); return m ? new Date(+m[1], +m[2]-1, +m[3]) : null; }
function dateToISOKP(d) { return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`; }

function KitEditor({ profile, kit, setKit }) {
  const set = (k) => (v) => setKit(prev => ({ ...prev, [k]: v }));
  const money = (k) => (v) => setKit(prev => ({ ...prev, [k]: v.replace(/[^0-9.]/g, '') }));
  const onWE = (e) => { const sat = parseWeekEnding(e.target.value); set('weekEnding')(sat ? dateToISOKP(sat) : ''); };
  const sat = isoToDateKP(kit.weekEnding);
  const invCount = kitInventoryLines(kit.inventory).filter(Boolean).length;

  return (
    <>
      <Section title="Box rental">
        <Field label="Employee name" hint="from profile"><TextInput value={profile.fullName} placeholder="Set in Profile" disabled /></Field>
        <div className="grid2">
          <Field label="Company"><TextInput value={kit.company} onChange={set('company')} placeholder="Production company" /></Field>
          <Field label="Last 4 SSN" hint="from profile"><TextInput value={profile.ssnLast4} placeholder="1234" mono disabled /></Field>
        </div>
        <div className="grid2">
          <Field label="Kit type" hint="file name"><TextInput value={kit.kitType} onChange={(v) => set('kitType')(v.toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0,14))} placeholder="DRONE" mono /></Field>
          <Field label="Initials" hint="file name"><TextInput value={kit.initials} onChange={(v) => set('initials')(v.toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0,5))} placeholder={profile.initials || 'ABC'} mono /></Field>
        </div>
        <div className="grid2">
          <Field label="Rental rate" hint="$">
            <TextInput value={kit.rentalRate} onChange={money('rentalRate')} placeholder="0.00" mono />
          </Field>
          <Field label="Per">
            <div className="seg full">
              <button className={'seg-btn' + (kit.rentalPer === 'day' ? ' on' : '')} onClick={() => set('rentalPer')('day')}>Day</button>
              <button className={'seg-btn' + (kit.rentalPer === 'week' ? ' on' : '')} onClick={() => set('rentalPer')('week')}>Week</button>
            </div>
          </Field>
        </div>
        <Field label="Week ending" hint="Saturday">
          <input type="date" className="tin mono" value={kit.weekEnding || ''} onChange={onWE} />
        </Field>
        {sat && <div className="we-hint mono">W/E {fmtDateMMDDYY(sat)}</div>}
      </Section>

      <Section title="Inventory" right={<span className="muted sm">{invCount}/8 lines</span>}>
        <textarea className="paste" rows={6} value={kit.inventory}
          placeholder={"One item per line"}
          onChange={(e) => set('inventory')(e.target.value)} spellCheck={false}></textarea>
        <Field label="Inventory (check one)">
          <div className="seg full">
            <button className={'seg-btn' + (kit.invCheck === '' ? ' on' : '')} onClick={() => set('invCheck')('')}>None</button>
            <button className={'seg-btn' + (kit.invCheck === 'onfile' ? ' on' : '')} onClick={() => set('invCheck')('onfile')}>On file</button>
            <button className={'seg-btn' + (kit.invCheck === 'attached' ? ' on' : '')} onClick={() => set('invCheck')('attached')}>Attached</button>
          </div>
        </Field>
      </Section>

      <Section title="Signature & date">
        <div className="sig-thumb-row">
          {profile.signature
            ? <div className="sig-thumb"><img src={profile.signature} alt="signature" /></div>
            : <span className="muted sm">No signature on file — add one from the time card tab or profile.</span>}
        </div>
        <Field label="Date" hint="signature date">
          <input type="date" className="tin mono" value={kit.date || ''} onChange={(e) => set('date')(e.target.value)} />
        </Field>
      </Section>
    </>
  );
}
// name/ssn come from profile and are shown read-only here; editing happens in Profile.

function SavedKitList({ kits, activeId, onOpen, onDelete }) {
  return (
    <div className="saved">
      <div className="saved-head">
        <span className="rail-label">Saved kit forms</span>
        {kits.length > 0 && <span className="rail-count mono">{kits.length}</span>}
      </div>
      {kits.length === 0 && <p className="muted sm pad">No saved kit forms yet.</p>}
      <ul className="saved-list">
        {kits.map(k => (
          <li key={k.id} className={'saved-item' + (k.id === activeId ? ' on' : '')} onClick={() => onOpen(k.id)}>
            <div className="si-main">
              <div className="si-title">{k.company || 'Untitled'}</div>
              <div className="si-sub mono">W/E {k.weekEndingStr || '—'}</div>
            </div>
            <button className="si-del" title="Delete" onClick={(e) => { e.stopPropagation(); onDelete(k.id); }}>✕</button>
          </li>
        ))}
      </ul>
    </div>
  );
}

Object.assign(window, { KitEditor, SavedKitList });
