// RM.jsx — R&M Overview: Repair tickets (left) + Maintenance schedule with countdown (right)
// Replaces Repairs.jsx — surfaces overdue maintenance prominently

function countdownClass(daysLeft) {
  if (daysLeft < 0) return 'countdown-pill--overdue';
  if (daysLeft <= 14) return 'countdown-pill--soon';
  return 'countdown-pill--ok';
}

function countdownLabel(daysLeft) {
  if (daysLeft < 0) return Math.abs(daysLeft) + 'd OVERDUE';
  if (daysLeft === 0) return 'DUE TODAY';
  return daysLeft + 'd left';
}

function RMPage({ role }) {
  const [tab, setTab] = React.useState('overview'); // overview | repair | maintenance
  const [editingMt, setEditingMt] = React.useState(null);
  const [intervalDraft, setIntervalDraft] = React.useState(90);
  // Open the AppSheet-style form modal. null when closed; 'schedule' | 'ticket' when open.
  const [addForm, setAddForm] = React.useState(null);
  const [toast, setToast] = React.useState(null);
  const [search, setSearch] = React.useState('');

  const canEdit = role === 'Admin' || role === 'Mechanic';

  // ===== Full-text search across both datasets (customer/plate/operator-style:
  // here it spans machine, issue/type, mechanic, ticket id, priority, status). =====
  const q = search.trim().toLowerCase();
  const matches = (obj) => !q || Object.values(obj).some(v => String(v ?? '').toLowerCase().includes(q));
  const repairRows = REPAIR_TICKETS.filter(matches);
  const maintRows = MAINTENANCE.filter(matches);

  const overdue = maintRows.filter(m => m.days_left < 0).sort((a, b) => a.days_left - b.days_left);
  const soon = maintRows.filter(m => m.days_left >= 0 && m.days_left <= 14);

  const repairsActive = repairRows.filter(r => r.status !== 'Completed');
  const repairsDone = repairRows.filter(r => r.status === 'Completed');

  const startEditMt = (m) => { setEditingMt(m.id); setIntervalDraft(m.interval_days); };

  return (
    <div className="page">
      {/* Overdue banner */}
      {overdue.length > 0 ? (
        <div className="rm-overdue-banner">
          <div className="rm-overdue-banner__icon"><AlertTriangle size={18}/></div>
          <div style={{flex: 1}}>
            <div className="rm-overdue-banner__title">{overdue.length} overdue maintenance task{overdue.length === 1 ? '' : 's'}</div>
            <div className="rm-overdue-banner__sub">
              Worst: <strong>{overdue[0].machine}</strong> — {overdue[0].type} is {Math.abs(overdue[0].days_left)} days overdue.
              Schedule service ASAP to avoid downtime risk.
            </div>
          </div>
          <button className="btn btn--primary" onClick={() => setTab('maintenance')}>
            Review Schedule <ChevronRight size={14}/>
          </button>
        </div>
      ) : null}

      {/* Tabs */}
      <div className="tab-bar">
        <button className={"tab-btn " + (tab === 'overview' ? 'tab-btn--active' : '')} onClick={() => setTab('overview')}>
          <Activity size={14}/> Overview
        </button>
        <button className={"tab-btn " + (tab === 'repair' ? 'tab-btn--active' : '')} onClick={() => setTab('repair')}>
          <Wrench size={14}/> Repair Tickets ({repairsActive.length} active)
        </button>
        <button className={"tab-btn " + (tab === 'maintenance' ? 'tab-btn--active' : '')} onClick={() => setTab('maintenance')}>
          <Clock size={14}/> Maintenance Schedule ({MAINTENANCE.length})
        </button>
      </div>

      {/* Full-text search — spans repair tickets + maintenance schedule */}
      <div style={{position: 'relative', maxWidth: 560, margin: '0 0 16px'}}>
        <Search size={18} style={{position: 'absolute', left: 14, top: '50%', transform: 'translateY(-50%)', color: 'var(--color-grey-500)', pointerEvents: 'none'}}/>
        <input
          value={search}
          onChange={e => setSearch(e.target.value)}
          placeholder="Search R&amp;M — machine, plate, issue, mechanic, status..."
          className="input"
          style={{height: 48, paddingLeft: 44, paddingRight: search ? 40 : 14, width: '100%', fontSize: 15, borderRadius: 12}}/>
        {search ? (
          <button type="button" onClick={() => setSearch('')}
            aria-label="Clear search"
            style={{position: 'absolute', right: 8, top: '50%', transform: 'translateY(-50%)', width: 28, height: 28, borderRadius: 7, border: 'none', background: 'var(--color-grey-100)', color: 'var(--color-grey-600)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center'}}>
            <X size={15}/>
          </button>
        ) : null}
      </div>

      {tab === 'overview' ? (
        <div className="rm-grid">
          {/* Left: Repair side */}
          <div className="card rm-ov-card">
            <div className="card__header">
              <div>
                <h3 className="card__title">Active Repairs</h3>
                <div className="card__sub">Unscheduled fault tickets</div>
              </div>
              <span className="status status--orange">{repairsActive.length} open</span>
            </div>
            <div className="card__body" style={{padding: 0}}>
              {repairsActive.map(r => (
                <div key={r.id} style={{padding: '14px 18px', borderBottom: '1px solid var(--color-grey-100)'}}>
                  <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 8}}>
                    <div style={{flex: 1}}>
                      <div style={{fontFamily: 'monospace', fontSize: 11, color: 'var(--color-grey-500)'}}>{r.id}</div>
                      <div style={{fontWeight: 600, fontSize: 14, color: 'var(--color-navy)'}}>{r.machine}</div>
                      <div style={{fontSize: 13, color: 'var(--color-grey-700)', marginTop: 4}}>{r.issue}</div>
                      <div style={{fontSize: 12, color: 'var(--color-grey-500)', marginTop: 4}}>
                        Mechanic: {r.mechanic} · Opened {r.opened}
                      </div>
                    </div>
                    <span className={"status status--" + (r.priority === 'High' ? 'red' : r.priority === 'Medium' ? 'yellow' : 'gray')}>{r.priority}</span>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* Right: Maintenance side */}
          <div className="card rm-ov-card">
            <div className="card__header">
              <div>
                <h3 className="card__title">Upcoming Maintenance</h3>
                <div className="card__sub">Recurring schedule · Days countdown</div>
              </div>
              {overdue.length > 0 ? <span className="status status--red">{overdue.length} overdue</span> : <span className="status status--green">on track</span>}
            </div>
            <div className="card__body" style={{padding: 0}}>
              {[...overdue, ...soon].slice(0, 8).map(m => (
                <div key={m.id} style={{padding: '14px 18px', borderBottom: '1px solid var(--color-grey-100)', display: 'flex', alignItems: 'center', gap: 12}}>
                  <div style={{flex: 1}}>
                    <div style={{fontWeight: 600, fontSize: 14, color: 'var(--color-navy)'}}>{m.machine}</div>
                    <div style={{fontSize: 13, color: 'var(--color-grey-700)'}}>{m.type}</div>
                    <div style={{fontSize: 11, color: 'var(--color-grey-500)', marginTop: 2}}>
                      Last: {m.last} · Every {m.months} mo
                    </div>
                  </div>
                  <span className={"countdown-pill " + countdownClass(m.days_left)}>
                    {countdownLabel(m.days_left)}
                  </span>
                </div>
              ))}
            </div>
          </div>
        </div>
      ) : null}

      {tab === 'repair' ? (
        <div className="card">
          <div className="card__header">
            <div>
              <h3 className="card__title">All Repair Tickets</h3>
              <div className="card__sub">Workshop fault queue</div>
            </div>
            {canEdit ? <button className="btn btn--primary" onClick={() => setAddForm('ticket')}><Plus size={14}/> New Ticket</button> : null}
          </div>
          <div className="card__body" style={{padding: 0, overflowX: 'auto'}}>
            <table className="table">
              <thead>
                <tr>
                  <th>Ticket</th><th>Machine</th><th>Issue</th><th>Priority</th>
                  <th>Mechanic</th><th>Cost</th><th>Status</th>
                </tr>
              </thead>
              <tbody>
                {repairRows.map(r => (
                  <tr key={r.id}>
                    <td style={{fontFamily: 'monospace', fontSize: 12}}>{r.id}</td>
                    <td style={{fontWeight: 600}}>{r.machine}</td>
                    <td>{r.issue}</td>
                    <td><span className={"status status--" + (r.priority === 'High' ? 'red' : r.priority === 'Medium' ? 'yellow' : 'gray')}>{r.priority}</span></td>
                    <td>{r.mechanic}</td>
                    <td>{r.cost}</td>
                    <td><span className={"status status--" + (r.status === 'Completed' ? 'green' : r.status === 'In Progress' ? 'orange' : 'blue')}>{r.status}</span></td>
                  </tr>
                ))}
                {repairRows.length === 0 ? (
                  <tr><td colSpan={7} style={{padding: 28, textAlign: 'center', color: 'var(--color-grey-500)', fontSize: 14}}>No repair tickets match “{search}”</td></tr>
                ) : null}
              </tbody>
            </table>
          </div>
        </div>
      ) : null}

      {tab === 'maintenance' ? (
        <div className="card">
          <div className="card__header">
            <div>
              <h3 className="card__title">Maintenance Schedule</h3>
              <div className="card__sub">Recurring · Fixed countdown period per service item (months)</div>
            </div>
            {canEdit ? <button className="btn btn--primary" onClick={() => setAddForm('schedule')}><Plus size={14}/> Add Schedule</button> : null}
          </div>
          <div className="card__body" style={{padding: 0, overflowX: 'auto'}}>
            <table className="table">
              <thead>
                <tr>
                  <th>Machine</th><th>Service Item</th><th>Last Done</th>
                  <th>Next Due</th><th>Interval (fixed)</th><th>Countdown</th>
                </tr>
              </thead>
              <tbody>
                {maintRows.sort((a, b) => a.days_left - b.days_left).map(m => (
                  <tr key={m.id}>
                    <td style={{fontWeight: 600}}>{m.machine}</td>
                    <td>{m.type}</td>
                    <td style={{fontSize: 13}}>{m.last}</td>
                    <td style={{fontSize: 13}}>{m.next}</td>
                    <td>
                      <span style={{fontFamily: 'monospace', display: 'inline-flex', alignItems: 'center', gap: 5}}>
                        {m.months} mo <Lock size={11} style={{color: 'var(--color-grey-400)'}}/>
                      </span>
                    </td>
                    <td>
                      <span className={"countdown-pill " + countdownClass(m.days_left)}>
                        {countdownLabel(m.days_left)}
                      </span>
                    </td>
                  </tr>
                ))}
                {maintRows.length === 0 ? (
                  <tr><td colSpan={6} style={{padding: 28, textAlign: 'center', color: 'var(--color-grey-500)', fontSize: 14}}>No maintenance schedules match “{search}”</td></tr>
                ) : null}
              </tbody>
            </table>
          </div>
          {!canEdit ? (
            <div style={{padding: 12, fontSize: 12, color: 'var(--color-grey-500)', borderTop: '1px solid var(--color-grey-200)'}}>
              <Lock size={11} style={{verticalAlign: 'middle'}}/> Service intervals are fixed per item (in months) and apply to every crane. Adding schedules is restricted to Admin and Mechanic roles.
            </div>
          ) : null}
        </div>
      ) : null}

      {/* AppSheet-style add form */}
      {addForm ? (
        <AddRMForm
          mode={addForm}
          onClose={() => setAddForm(null)}
          onSubmit={(payload) => {
            setAddForm(null);
            setToast(payload.mode === 'schedule' ? 'Schedule saved' : 'Ticket created');
            window.setTimeout(() => setToast(null), 2600);
          }}
        />
      ) : null}

      {/* Success toast */}
      {toast ? (
        <div style={{
          position: 'fixed', bottom: 24, left: '50%', transform: 'translateX(-50%)',
          background: 'var(--color-navy)', color: 'white', padding: '12px 20px',
          borderRadius: 10, display: 'flex', alignItems: 'center', gap: 10,
          boxShadow: '0 12px 30px rgba(11,31,58,0.35)', zIndex: 1200, fontSize: 14, fontWeight: 600,
        }}>
          <Check size={16}/> {toast}
        </div>
      ) : null}
    </div>
  );
}

// ====================================================================
// AddRMForm — AppSheet-style modal used for both "Add Schedule" and "New
// Ticket". The two modes share most fields; only labels/required-flags and
// a couple of dropdown sources differ. Built to mirror the AppSheet input
// the user is familiar with on mobile (label above, outlined input, red *
// for required, read-only fields appear muted).
// ====================================================================
function AddRMForm({ mode, onClose, onSubmit }) {
  const isSchedule = mode === 'schedule';
  const today = new Date();
  const todayISO = today.toISOString().slice(0, 10);

  // Form state
  const [date, setDate] = React.useState(todayISO);
  const [category, setCategory] = React.useState('');
  const [machine, setMachine] = React.useState('');
  const [serviceItem, setServiceItem] = React.useState('');
  const [operator, setOperator] = React.useState('');
  const [info, setInfo] = React.useState('');
  const [supplier, setSupplier] = React.useState('');
  const [mechanic, setMechanic] = React.useState('');
  const [showErrors, setShowErrors] = React.useState(false);

  // Capture "Added" timestamp ONCE on mount so it doesn't tick while user
  // is filling the form. Matches AppSheet behaviour.
  const addedTs = React.useRef(new Date()).current;

  // Derived: human-readable formatted date — "24 May 2026 (Sun)"
  const formattedDate = React.useMemo(() => {
    if (!date) return '';
    const d = new Date(date + 'T00:00:00');
    const dd = d.getDate();
    const mon = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'][d.getMonth()];
    const yr = d.getFullYear();
    const dow = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'][d.getDay()];
    return `${dd} ${mon} ${yr} (${dow})`;
  }, [date]);

  // Derived: Days_Left = date - today (positive = upcoming, negative = overdue)
  const daysLeft = React.useMemo(() => {
    if (!date) return 0;
    const a = new Date(date + 'T00:00:00');
    const b = new Date(todayISO + 'T00:00:00');
    return Math.round((a - b) / 86400000);
  }, [date, todayISO]);

  // Service items — schedule mode pulls the FIXED service catalog (months);
  // ticket mode uses common repair issue templates.
  const SERVICE_ITEMS_SCHEDULE = SERVICE_ITEMS.map(s => s.item);
  const SERVICE_ITEMS_TICKET = [
    'Hydraulic leak',
    'Engine fault',
    'Slew gear noise',
    'Outrigger drift',
    'Boom inspection',
    'Electrical fault',
    'Tyre / wheel',
    'Other (see Info)',
  ];
  const serviceItems = isSchedule ? SERVICE_ITEMS_SCHEDULE : SERVICE_ITEMS_TICKET;

  // Machines filtered by chosen category
  const machinesForCat = category ? MACHINES.filter(m => m.category === category) : MACHINES;

  // Reset machine if category changes and current machine is no longer in list
  React.useEffect(() => {
    if (machine && category) {
      const m = MACHINES.find(x => x.id === machine || x.name === machine);
      if (!m || m.category !== category) setMachine('');
    }
  }, [category]);

  // Required-field check — Date, Service_Item, Category, Machine are required.
  const errors = {
    date: !date,
    serviceItem: !serviceItem,
    category: !category,
    machine: !machine,
  };
  const hasErrors = Object.values(errors).some(Boolean);

  const handleSubmit = () => {
    if (hasErrors) { setShowErrors(true); return; }
    if (onSubmit) onSubmit({
      mode, date, formattedDate, daysLeft, serviceItem, category,
      machine, operator, info, supplier, mechanic, addedTs,
    });
  };

  // Esc to close
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose && onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);

  // === Inline styled primitives ====================================
  const labelStyle = { display: 'block', fontSize: 13, color: 'var(--color-grey-700)', marginBottom: 6, fontWeight: 500 };
  const reqStar = <span style={{color: 'var(--color-yellow-700, #d97706)', marginLeft: 2, fontWeight: 700}}>*</span>;
  const inputBase = {
    width: '100%', height: 44, padding: '0 14px',
    border: '1px solid var(--color-grey-300)', borderRadius: 8,
    fontSize: 15, color: 'var(--color-grey-900, #111827)',
    background: 'white', boxSizing: 'border-box',
    fontFamily: 'inherit', outline: 'none',
  };
  const inputErr = { borderColor: '#dc2626', background: '#fef2f2' };
  const inputReadonly = { background: 'var(--color-grey-50)', color: 'var(--color-grey-500)' };

  // Reusable "field row" — label on top, input below, validation msg under.
  const Field = ({ label, required, hint, error, children }) => (
    <div style={{marginBottom: 18}}>
      <label style={labelStyle}>{label}{required ? reqStar : null}</label>
      {children}
      {hint ? <div style={{fontSize: 12, color: 'var(--color-grey-500)', marginTop: 4}}>{hint}</div> : null}
      {error ? <div style={{fontSize: 12, color: '#dc2626', marginTop: 4, display: 'flex', alignItems: 'center', gap: 4}}><AlertTriangle size={12}/> {error}</div> : null}
    </div>
  );

  // Format "Added" for read-only field — dd/mm/yyyy, hh:mm:ss AM/PM
  const fmtAdded = (d) => {
    const dd = String(d.getDate()).padStart(2, '0');
    const mm = String(d.getMonth() + 1).padStart(2, '0');
    const yy = d.getFullYear();
    let h = d.getHours();
    const ap = h >= 12 ? 'PM' : 'AM';
    h = h % 12; if (h === 0) h = 12;
    const mi = String(d.getMinutes()).padStart(2, '0');
    const se = String(d.getSeconds()).padStart(2, '0');
    return `${dd}/${mm}/${yy}, ${String(h).padStart(2,'0')}:${mi}:${se} ${ap}`;
  };

  return (
    <div className="install-modal" onClick={onClose} style={{padding: 0, alignItems: 'stretch'}}>
      <div onClick={(e) => e.stopPropagation()}
        style={{
          background: 'white', width: '100%', maxWidth: 560, maxHeight: '94vh',
          margin: 'auto', borderRadius: 14, display: 'flex', flexDirection: 'column',
          boxShadow: '0 24px 56px rgba(11,31,58,0.30)',
        }}>
        {/* Header — navy bar so it matches the rest of the dashboard chrome */}
        <div style={{
          padding: '16px 22px', background: 'var(--color-navy)', color: 'white',
          borderRadius: '14px 14px 0 0', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        }}>
          <div>
            <div style={{fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase', opacity: 0.7, fontWeight: 600}}>
              {isSchedule ? 'Maintenance' : 'Workshop'}
            </div>
            <div style={{fontSize: 18, fontWeight: 700, marginTop: 2}}>
              {isSchedule ? 'Add Schedule' : 'Add New Ticket'}
            </div>
          </div>
          <button type="button" onClick={onClose}
            style={{background: 'rgba(255,255,255,0.10)', border: 'none', color: 'white', width: 32, height: 32, borderRadius: 8, display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer'}}>
            <X size={18}/>
          </button>
        </div>

        {/* Scrollable form body */}
        <div style={{padding: '20px 22px', overflowY: 'auto', flex: 1}}>

          {/* Date (editable) */}
          <Field label="Date" required
            error={showErrors && errors.date ? 'Date is required' : null}>
            <div style={{position: 'relative'}}>
              <input type="date" value={date} onChange={e => setDate(e.target.value)}
                style={{...inputBase, paddingRight: 44, ...(showErrors && errors.date ? inputErr : {})}}/>
              <Calendar size={18} style={{position: 'absolute', right: 14, top: '50%', transform: 'translateY(-50%)', color: 'var(--color-grey-500)', pointerEvents: 'none'}}/>
            </div>
          </Field>

          {/* Date (display, read-only — auto-formatted) */}
          <Field label="Date">
            <input value={formattedDate} readOnly style={{...inputBase, ...inputReadonly}}/>
          </Field>

          {/* Days_Left (auto-computed) */}
          <Field label="Days_Left"
            hint={!isSchedule ? 'Days from today until this ticket\'s target date.' : 'Auto-counts down each day until service is done.'}>
            <input value={daysLeft.toFixed(2)} readOnly
              style={{
                ...inputBase, ...inputReadonly,
                color: daysLeft < 0 ? '#dc2626' : daysLeft <= 14 ? '#d97706' : 'var(--color-grey-700)',
                fontWeight: daysLeft < 0 ? 700 : 500,
              }}/>
          </Field>

          {/* Service_Item (dropdown) */}
          <Field label={isSchedule ? 'Service_Item' : 'Issue_Item'} required
            error={showErrors && errors.serviceItem ? (isSchedule ? 'Service item is required' : 'Issue is required') : null}>
            <div style={{position: 'relative'}}>
              <select value={serviceItem} onChange={e => setServiceItem(e.target.value)}
                style={{...inputBase, appearance: 'none', paddingRight: 44, color: serviceItem ? 'inherit' : 'var(--color-grey-400)', ...(showErrors && errors.serviceItem ? inputErr : {})}}>
                <option value="">{isSchedule ? '— Select service item —' : '— Select issue —'}</option>
                {serviceItems.map(s => <option key={s} value={s}>{s}</option>)}
              </select>
              <ChevDown size={16} style={{position: 'absolute', right: 14, top: '50%', transform: 'translateY(-50%)', color: 'var(--color-grey-500)', pointerEvents: 'none'}}/>
            </div>
          </Field>

          {/* Interval (fixed) — auto-filled from the service catalog, read-only */}
          {isSchedule ? (
            <Field label="Interval (fixed)"
              hint={serviceItem ? 'This item\u2019s countdown period is fixed and cannot be changed here.' : 'Pick a service item to see its fixed countdown period.'}>
              <div style={{position: 'relative'}}>
                <input
                  value={serviceItem && SERVICE_INTERVAL_MONTHS[serviceItem] != null ? SERVICE_INTERVAL_MONTHS[serviceItem] + ' months' : ''}
                  readOnly
                  placeholder="—"
                  style={{...inputBase, ...inputReadonly, paddingRight: 44}}/>
                <Lock size={16} style={{position: 'absolute', right: 14, top: '50%', transform: 'translateY(-50%)', color: 'var(--color-grey-400)', pointerEvents: 'none'}}/>
              </div>
            </Field>
          ) : null}
          <Field label="Category" required
            error={showErrors && errors.category ? 'Category is required' : null}>
            <div style={{position: 'relative'}}>
              <select value={category} onChange={e => setCategory(e.target.value)}
                style={{...inputBase, appearance: 'none', paddingRight: 44, color: category ? 'inherit' : 'var(--color-grey-400)', ...(showErrors && errors.category ? inputErr : {})}}>
                <option value="">— Select category —</option>
                {CATEGORIES.map(c => <option key={c.id} value={c.name}>{c.name}</option>)}
              </select>
              <ChevDown size={16} style={{position: 'absolute', right: 14, top: '50%', transform: 'translateY(-50%)', color: 'var(--color-grey-500)', pointerEvents: 'none'}}/>
            </div>
          </Field>

          {/* Machine */}
          <Field label="Machine" required
            hint={category ? `${machinesForCat.length} machine${machinesForCat.length === 1 ? '' : 's'} in ${category}` : 'Pick a category first to narrow the list.'}
            error={showErrors && errors.machine ? 'Machine is required' : null}>
            <div style={{position: 'relative'}}>
              <select value={machine} onChange={e => setMachine(e.target.value)}
                disabled={!category}
                style={{...inputBase, appearance: 'none', paddingRight: 44, color: machine ? 'inherit' : 'var(--color-grey-400)', ...(showErrors && errors.machine ? inputErr : {}), ...(!category ? inputReadonly : {})}}>
                <option value="">— Select machine —</option>
                {machinesForCat.map(m => (
                  <option key={m.id} value={m.id}>{m.id} · {machineLabel(m)}</option>
                ))}
              </select>
              <ChevDown size={16} style={{position: 'absolute', right: 14, top: '50%', transform: 'translateY(-50%)', color: 'var(--color-grey-500)', pointerEvents: 'none'}}/>
            </div>
          </Field>

          {/* Operator */}
          <Field label="Operator"
            hint="Optional — the operator regularly assigned to this machine.">
            <div style={{position: 'relative'}}>
              <select value={operator} onChange={e => setOperator(e.target.value)}
                style={{...inputBase, appearance: 'none', paddingRight: 44, color: operator ? 'inherit' : 'var(--color-grey-400)'}}>
                <option value="">— Select operator —</option>
                {OPERATORS.map(o => <option key={o.id} value={o.name}>{o.name}</option>)}
              </select>
              <ChevDown size={16} style={{position: 'absolute', right: 14, top: '50%', transform: 'translateY(-50%)', color: 'var(--color-grey-500)', pointerEvents: 'none'}}/>
            </div>
          </Field>

          {/* Info — multi-line for context */}
          <Field label="Info" hint="Free notes — symptoms, parts pre-ordered, site reminders.">
            <textarea value={info} onChange={e => setInfo(e.target.value)}
              placeholder=""
              style={{...inputBase, height: 'auto', minHeight: 80, padding: '12px 14px', resize: 'vertical', lineHeight: 1.4}}/>
          </Field>

          {/* Supplier */}
          <Field label="Supplier" hint={isSchedule ? 'Parts/oil supplier for this service.' : 'Parts supplier handling this repair.'}>
            <div style={{position: 'relative'}}>
              <select value={supplier} onChange={e => setSupplier(e.target.value)}
                style={{...inputBase, appearance: 'none', paddingRight: 44, color: supplier ? 'inherit' : 'var(--color-grey-400)'}}>
                <option value="">— Select supplier —</option>
                {SUPPLIERS.map(s => <option key={s} value={s}>{s}</option>)}
              </select>
              <ChevDown size={16} style={{position: 'absolute', right: 14, top: '50%', transform: 'translateY(-50%)', color: 'var(--color-grey-500)', pointerEvents: 'none'}}/>
            </div>
          </Field>

          {/* Mechanic */}
          <Field label="Mechanic" hint="Workshop mechanic responsible.">
            <div style={{position: 'relative'}}>
              <select value={mechanic} onChange={e => setMechanic(e.target.value)}
                style={{...inputBase, appearance: 'none', paddingRight: 44, color: mechanic ? 'inherit' : 'var(--color-grey-400)'}}>
                <option value="">— Select mechanic —</option>
                {MECHANICS.map(m => <option key={m} value={m}>{m}</option>)}
              </select>
              <ChevDown size={16} style={{position: 'absolute', right: 14, top: '50%', transform: 'translateY(-50%)', color: 'var(--color-grey-500)', pointerEvents: 'none'}}/>
            </div>
          </Field>

          {/* Added — read-only timestamp */}
          <Field label="Added" hint="System timestamp — set automatically when you submit.">
            <div style={{position: 'relative'}}>
              <input value={fmtAdded(addedTs)} readOnly
                style={{...inputBase, ...inputReadonly, paddingRight: 44}}/>
              <Calendar size={18} style={{position: 'absolute', right: 14, top: '50%', transform: 'translateY(-50%)', color: 'var(--color-grey-500)', pointerEvents: 'none'}}/>
            </div>
          </Field>

          {showErrors && hasErrors ? (
            <div style={{padding: 12, background: '#fef2f2', border: '1px solid #fecaca', borderLeft: '4px solid #dc2626', borderRadius: 8, color: '#991b1b', fontSize: 13, display: 'flex', alignItems: 'flex-start', gap: 8, marginTop: 4}}>
              <AlertTriangle size={16} style={{flexShrink: 0, marginTop: 1}}/>
              <div>
                <strong>Missing required fields.</strong> Fill in the highlighted fields marked <span style={{color: '#d97706', fontWeight: 700}}>*</span> before saving.
              </div>
            </div>
          ) : null}
        </div>

        {/* Footer */}
        <div style={{padding: '14px 22px', borderTop: '1px solid var(--color-grey-200)', display: 'flex', gap: 10, justifyContent: 'flex-end', background: 'var(--color-grey-50)', borderRadius: '0 0 14px 14px'}}>
          <button type="button" className="btn btn--ghost" onClick={onClose}>Cancel</button>
          <button type="button" className="btn btn--primary" onClick={handleSubmit}>
            <Check size={14}/> {isSchedule ? 'Save Schedule' : 'Create Ticket'}
          </button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { RMPage, AddRMForm });
