// tc-panels.jsx — Profile modal + the slim New Timecard editor.
const { useState: useStateP, useRef: useRefP } = React;

function isoToDate(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 dateToISO(d) { return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`; }
const MON = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
function fmtWeekRange(satDate) {
  if (!satDate) return '';
  const sun = new Date(satDate.getTime()); sun.setDate(satDate.getDate() - 6);
  return `${MON[sun.getMonth()]} ${sun.getDate()} – ${MON[satDate.getMonth()]} ${satDate.getDate()}, ${satDate.getFullYear()}`;
}

// ── Profile editor (modal): the stuff that's the same every week ─────────────
function ProfileModal({ open, profile, setProfile, onClose, onEditSignature, onBackup, onRestore }) {
  const set = (k) => (v) => setProfile(prev => ({ ...prev, [k]: v }));
  const restoreRef = useRefP(null);
  return (
    <Modal open={open} onClose={onClose} title="Your Profile" width={540}
      footer={<>
        <span className="muted sm">Saved to this browser. Flows into every form.</span>
        <Button variant="primary" onClick={onClose}>Done</Button>
      </>}>
      <div className="grid2">
        <Field label="Full name" className="span2"><TextInput value={profile.fullName} onChange={set('fullName')} placeholder="First Last" /></Field>
        <Field label="Occupation" className="span2"><TextInput value={profile.occupation} onChange={set('occupation')} placeholder="Occupation" /></Field>
        <Field label="SSN" hint="last 4"><TextInput value={profile.ssnLast4} onChange={v => set('ssnLast4')(v.replace(/\D/g, '').slice(0, 4))} placeholder="1234" mono maxLength={4} /></Field>
        <Field label="Initials" hint="for file names"><TextInput value={profile.initials} onChange={v => set('initials')(v.toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, 5))} placeholder="ABC" mono /></Field>
        <Field label="Default per diem" hint="$ / day" className="span2"><TextInput value={profile.perDiemRate} onChange={v => set('perDiemRate')(v.replace(/[^0-9.]/g, ''))} placeholder="0.00" mono /></Field>
      </div>
      <div className="profile-sig">
        <span className="field-label">Signature</span>
        <div className="profile-sig-row">
          {profile.signature
            ? <div className="sig-thumb lg"><img src={profile.signature} alt="signature" /></div>
            : <span className="muted sm">None yet</span>}
          <div className="profile-sig-actions">
            <Button onClick={onEditSignature}>{profile.signature ? 'Change signature' : '+ Add signature'}</Button>
            {profile.signature && <button className="link-btn" onClick={() => set('signature')('')}>Remove</button>}
          </div>
        </div>
      </div>
      <div className="profile-fname">
        <span className="field-label">Output file names</span>
        <p className="muted sm backup-note">Name each PDF your own way. Tap a token to insert it; type the rest. Leave blank for the default. <b>{'{TYPE}'}</b> becomes <b>TC</b> on a time card and <b>DRONEKIT</b> / <b>CAMERAKIT</b> (your kit type + “KIT”) on a kit.</p>

        <div className="fname-block">
          <span className="fname-sub">Time card</span>
          <TextInput value={profile.fileNamePatternTC} onChange={set('fileNamePatternTC')} placeholder={DEFAULT_FN_PATTERN} mono />
          <div className="fname-tokens">
            {['{INITIALS}', '{TYPE}', '{DATE}', '{DATELONG}', '{PROJECT}'].map(tok => (
              <button key={tok} type="button" className="tok-chip mono"
                onClick={() => set('fileNamePatternTC')(((profile.fileNamePatternTC || '') + tok))}>{tok}</button>
            ))}
            {profile.fileNamePatternTC ? <button type="button" className="link-btn" onClick={() => set('fileNamePatternTC')('')}>Reset</button> : null}
          </div>
          <div className="fname-eg mono">
            e.g. {applyFnPattern(profile.fileNamePatternTC, { INITIALS: profile.initials || 'ABC', TYPE: 'TC', DATE: '061326', DATELONG: '20260613', PROJECT: 'PROJECT' })}
          </div>
        </div>

        <div className="fname-block">
          <span className="fname-sub">Kit / box rental</span>
          <TextInput value={profile.fileNamePatternKit} onChange={set('fileNamePatternKit')} placeholder={DEFAULT_FN_PATTERN} mono />
          <div className="fname-tokens">
            {['{INITIALS}', '{TYPE}', '{DATE}', '{DATELONG}'].map(tok => (
              <button key={tok} type="button" className="tok-chip mono"
                onClick={() => set('fileNamePatternKit')(((profile.fileNamePatternKit || '') + tok))}>{tok}</button>
            ))}
            {profile.fileNamePatternKit ? <button type="button" className="link-btn" onClick={() => set('fileNamePatternKit')('')}>Reset</button> : null}
          </div>
          <div className="fname-eg mono">
            e.g. {applyFnPattern(profile.fileNamePatternKit, { INITIALS: profile.initials || 'ABC', TYPE: 'DRONEKIT', DATE: '061326', DATELONG: '20260613', PROJECT: '' })}
          </div>
        </div>
      </div>
    </Modal>
  );
}

// ── Time card basics: Week Ending (anchor) + Project title + last-4 SSN ──────
function TimeCardFields({ card, setCard, parsed, profile, setProfile }) {
  const set = (k) => (v) => setCard(prev => ({ ...prev, [k]: v }));
  const onWE = (e) => {
    const sat = parseWeekEnding(e.target.value);
    set('weekEnding')(sat ? dateToISO(sat) : '');
  };
  const sat = isoToDate(card.weekEnding);
  return (
    <Section title="Time card">
      <div className="grid2">
        <Field label="Week ending" hint="Saturday — set first">
          <input type="date" className="tin mono" value={card.weekEnding || ''} onChange={onWE} />
        </Field>
        <Field label="SSN" hint="last 4">
          <TextInput value={profile.ssnLast4} onChange={(v) => setProfile(p => ({ ...p, ssnLast4: v.replace(/\D/g, '').slice(0, 4) }))} placeholder="1234" mono maxLength={4} />
        </Field>
      </div>
      {sat && <div className="we-hint mono">W/E {fmtDateMMDDYY(sat)} · {fmtWeekRange(sat)}</div>}
      <Field label="Project title"><TextInput value={card.projectTitle} onChange={set('projectTitle')} placeholder="Production name" /></Field>
      <div className="grid2">
        <Field label="Employee name"><TextInput value={profile.fullName} onChange={(v) => setProfile(p => ({ ...p, fullName: v }))} placeholder="First Last" /></Field>
        <Field label="Initials" hint="file name"><TextInput value={card.initials} onChange={(v) => set('initials')(v.toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0,5))} placeholder={profile.initials || 'ABC'} mono /></Field>
      </div>
      <Field label="Occupation"><TextInput value={profile.occupation} onChange={(v) => setProfile(p => ({ ...p, occupation: v }))} placeholder="Occupation" /></Field>
    </Section>
  );
}

// ── Work location with city→state autofill + recents ─────────────────────────
function LocationFields({ card, setCard, recents, onCity, onUseRecent, onRegionBlur }) {
  return (
    <Section title="Work location">
      <div className="grid-loc">
        <Field label="Work city">
          <input className="tin" list="city-list" value={card.workCity || ''}
            placeholder="Los Angeles"
            onChange={(e) => onCity(e.target.value)} />
          <datalist id="city-list">
            {[...new Set([...Object.keys(CITY_STATE), ...Object.keys(INTL_CITIES)])].sort().map(c => <option key={c} value={c.replace(/\b\w/g, m => m.toUpperCase())} />)}
          </datalist>
        </Field>
        <Field label="State" hint="US 2 · intl 3">
          <input className="tin mono" list="region-list" value={card.workState || ''}
            placeholder="CA / GHA"
            onChange={(e) => setCard(p => ({ ...p, workState: e.target.value }))}
            onBlur={onRegionBlur} />
          <datalist id="region-list">
            {REGION_OPTIONS.map(r => <option key={r} value={r} />)}
          </datalist>
        </Field>
      </div>
      {recents.length > 0 && (
        <div className="recents">
          <span className="muted sm">Recent:</span>
          {recents.map((r, i) => (
            <button key={i} className="recent-chip" onClick={() => onUseRecent(r)}>
              {r.city || '—'}<span className="mono">{r.state}</span>
            </button>
          ))}
        </div>
      )}
    </Section>
  );
}

// ── Pay: per diem (auto) + box rental ────────────────────────────────────────
function PayFields({ profile, card, setCard, parsed }) {
  const rate = card.perDiemRate !== '' ? card.perDiemRate : profile.perDiemRate;
  const autoDays = parsed.perDiemDays;
  const days = effectivePerDiemDays(card, parsed);
  const overridden = card.perDiemDays !== '' && card.perDiemDays != null && parseInt(card.perDiemDays, 10) !== autoDays;
  const total = perDiemTotal(rate, days);
  const money = (k) => (v) => setCard(p => ({ ...p, [k]: v.replace(/[^0-9.]/g, '') }));
  return (
    <Section title="Pay">
      <div className="grid2">
        <Field label="Per diem" hint="$ / day">
          <TextInput value={card.perDiemRate} onChange={money('perDiemRate')}
            placeholder={profile.perDiemRate ? profile.perDiemRate : '0.00'} mono />
        </Field>
        <Field label="Box rental" hint="$ · 1099">
          <TextInput value={card.boxRental} onChange={money('boxRental')} placeholder="0.00" mono />
        </Field>
      </div>
      <div className="pd-days">
        <Field label="Per diem days" hint={`auto: ${autoDays}`}>
          <TextInput value={card.perDiemDays}
            onChange={(v) => setCard(p => ({ ...p, perDiemDays: v.replace(/[^0-9]/g, '') }))}
            placeholder={String(autoDays)} mono />
        </Field>
        <span className="pd-days-note muted sm">
          {overridden
            ? <>Manual — counting <b>{days}</b> of {autoDays} work/travel/down days. <button className="link-btn" onClick={() => setCard(p => ({ ...p, perDiemDays: '' }))}>Reset to auto</button></>
            : <>Defaults to every work, travel &amp; down day. Type a number to override.</>}
        </span>
      </div>
      <div className="pd-summary mono">
        <span className="muted">Per diem</span>
        <span>${fmtMoney(parseFloat(rate) || 0)} × {days} {days === 1 ? 'day' : 'days'}</span>
        <span className="muted">=</span>
        <strong>${fmtMoney(total)}</strong>
      </div>
    </Section>
  );
}

// ── Paste input ───────────────────────────────────────────────────────────────
function PasteInput({ value, onChange, parsed, autoMeal, onAutoMeal }) {
  const hrs = timecardHours(parsed);
  return (
    <Section title="Days & times" right={
      <label className="meal-toggle" title="Auto-fill the 1st meal: OUT = call + 6h, IN = call + 6h30m">
        <span>Auto fill lunch</span>
        <input type="checkbox" checked={autoMeal !== false} onChange={(e) => onAutoMeal(e.target.checked)} />
        <span className="switch" aria-hidden="true"></span>
      </label>
    }>
      <textarea className="paste mono" rows={7} value={value}
        placeholder={"6/8 8a-8p\n6/9 8a-6p kit\n6/10 home\n6/11 down\n6/12 travel"}
        onChange={(e) => onChange(e.target.value)} spellCheck={false}></textarea>
      <div className="legend">
        <div className="legend-head">One line per day, starting with the date</div>
        <div className="legend-row"><code>6/8 8a-8p</code><span>a work day — fills call, wrap &amp; meal</span></div>
        <div className="legend-row"><code>6/9 8a-8p kit</code><span>add a word → it prints in the notes box</span></div>
        <div className="legend-row"><code>6/10 home</code><span>day off — leaves the row blank</span></div>
        <div className="legend-row"><code>6/11 down</code><span>writes that word across the row</span></div>
        <div className="legend-row"><code>6/12 travel</code><span>a travel day</span></div>
      </div>
      {hrs.total > 0 && (
        <div className="hours-readout">
          <span className="hr-stat"><b className="mono">{fmtHours(hrs.total)}</b> hrs worked</span>
          {hrs.ot > 0
            ? <span className="hr-stat hr-ot"><b className="mono">{fmtHours(hrs.ot)}</b> OT</span>
            : <span className="hr-stat muted">no OT</span>}
          <span className="hr-stat muted sm">{hrs.workDays} {hrs.workDays === 1 ? 'day' : 'days'} · 12h+ = OT</span>
        </div>
      )}
      {parsed.errors && parsed.errors.length > 0 && (
        <div className="warn">{parsed.errors.map((e, i) => <div key={i}>⚠ {e}</div>)}</div>
      )}
    </Section>
  );
}

// ── Instructions (modal) ─────────────────────────────────────────────────────
function InstructionsModal({ open, onClose }) {
  return (
    <Modal open={open} onClose={onClose} title="How to use" width={660}
      footer={<Button variant="primary" onClick={onClose}>Got it</Button>}>
      <div className="howto">
        <div className="howto-hero">
          <img className="wm wm-light" src="assets/tg-wordmark.svg" alt="Timecard Genny" />
          <img className="wm wm-dark" src="assets/tg-wordmark-dark.svg" alt="Timecard Genny" />
        </div>
        <div className="howto-step">
          <span className="howto-num">1</span>
          <div>
            <b>Set up your profile once.</b> Click your name in the top right, then fill in your name, job, last 4 of your SSN, initials, and per diem rate. <b>Add your signature</b> here too: draw it with your mouse/finger or upload a photo of it. You have to add it once, and it stamps every PDF automatically from then on. Everything saves on this device and fills in on every form.
          </div>
        </div>
        <div className="howto-step">
          <span className="howto-num">2</span>
          <div>
            <b>Pick a form up top.</b> Time Card or Kit Rental.
          </div>
        </div>
        <div className="howto-step">
          <span className="howto-num">3</span>
          <div>
            <b>Set Week Ending first.</b> Pick any day in that week and it snaps to the Saturday, so all your dates line up.
          </div>
        </div>
        <div className="howto-step">
          <span className="howto-num">4</span>
          <div>
            <b>Type one line per day,</b> starting with the date:
            <ul className="howto-list">
              <li><code>6/8 8a-8p</code> - a work day. Call, wrap, and lunch fill in for you.</li>
              <li><code>6/9 8a-8p kit</code> - add a word after the time and it prints in the notes box (kit, drone, OT).</li>
              <li><code>6/10 home</code> - a day off. Leaves the row blank.</li>
              <li><code>6/11 down</code> - writes that word across the row (down, hold, dark, wx).</li>
              <li><code>6/12 travel</code> - a travel day.</li>
            </ul>
            Want to set your own lunch times? Turn off <b>Auto fill lunch</b> (the toggle next to &ldquo;Days and times&rdquo;) and type them in yourself.
            <div className="howto-eg">
              <span className="howto-eg-label">Tip: keep your on-set notes in this exact shape and pasting them in is instant.</span>
              <pre className="howto-eg-pre">{`Week ending 06/20/2026
6/14 TRAVEL
6/15 8a-8p
6/16 8a-8p DRONE
6/17 DARK
6/18 8a-12a
6/19 10a-11p
6/20 TRAVEL`}</pre>
            </div>
          </div>
        </div>
        <div className="howto-step">
          <span className="howto-num">5</span>
          <div>
            <b>Set the work location.</b> Type the city (like <i>Los Angeles</i>) and the state fills in for you.
            <ul className="howto-list">
              <li><b>In the US,</b> the State box is <b>2 letters</b>: <code>CA</code>, <code>NY</code>, <code>TX</code>.</li>
              <li><b>Another country</b> is <b>3 letters</b>: <code>GBR</code>, <code>FRA</code>, <code>GHA</code>.</li>
              <li>You can type the full name (like <i>California</i> or <i>France</i>) and it shortens itself.</li>
            </ul>
            Places you&rsquo;ve used before show up as one-tap buttons, so you can pick them in a click.
          </div>
        </div>
        <div className="howto-step">
          <span className="howto-num">6</span>
          <div>
            <b>Check the pay.</b> Per diem adds itself up (rate &times; days). Didn&rsquo;t get it every day? Change the <i>Per diem days</i> number. Add a box rental if you have one.
          </div>
        </div>
        <div className="howto-step">
          <span className="howto-num">7</span>
          <div>
            <b>Hit Generate PDF.</b> It fills the real form and downloads it, ready to send. No need to hit save, your card saves itself as you type, so it&rsquo;s always waiting for you in your Library.
          </div>
        </div>
        <div className="howto-tips">
          <span className="howto-tips-h">Good to know</span>
          <ul className="howto-list">
            <li><b>Hours and OT add up as you type.</b> Anything over 12 hours in a day counts as overtime. Totals show under the days box and in the Saved menu.</li>
            <li><b>Everything saves by itself as you type.</b> No save button, nothing to remember. Reopen any card from your Library (top bar).</li>
            <li><b>Organize your Library into folders.</b> Open your Library and hit <b>New folder</b> (name it whatever you like, like a show or client). Hover any card and use the <b>{'\u25A4'}</b> button to drop it into a folder. Cards you haven&rsquo;t filed group by project title on their own. Rename or remove a folder with the {'\u270E'} / {'\uD83D\uDDD1'} icons, the cards inside stay safe.</li>
            <li><b>Delete a card.</b> Hover it in your Library and click the <b>{'\u00D7'}</b> in the corner. It asks you to confirm first, so nothing disappears by accident.</li>
            <li><b>Need to fill a box we don&rsquo;t?</b> Click Add text, then click any empty spot on the form and type. Drag to move it, A&minus; / A+ to resize, &times; to delete. It prints into the PDF and saves with the card.</li>
            <li><b>Customize (top bar)</b> changes fonts, colors, and size on screen only. It never changes the PDF.</li>
            <li><b>Everything saves by itself as you type.</b> No save button, nothing to remember. Reopen any card from the Saved menu.</li>
            <li><b>Rename your downloads</b> under Profile, Output file names.</li>
          </ul>
        </div>
      </div>
    </Modal>
  );
}

Object.assign(window, { ProfileModal, InstructionsModal, TimeCardFields, LocationFields, PayFields, PasteInput, isoToDate, dateToISO });
