/* global window, React */
// ============================================================
// Trip-action modals: Hold, Cancel, Split.
// All three follow the same anatomy:
//   1. Eyebrow + title + sub explaining what status moves where
//   2. Body — context-specific inputs (reason, dates, drop selectors)
//   3. Agent impact panel — what re-runs after you save
//   4. Foot — Cancel | confirm-CTA
// ============================================================

const { useState: useTAState } = React;

// ============================================================
// HoldModal — pauses dispatch; needs reason + when to revisit
// ============================================================
function HoldModal({ trip, onCancel, onConfirm }) {
  const [reason, setReason] = useTAState('inventory');
  const [until, setUntil]   = useTAState('next-wave');
  const [note, setNote]     = useTAState('');

  const reasons = [
    { v: 'inventory', label: 'Inventory pending', hint: 'WMS will release when stock arrives' },
    { v: 'customer',  label: 'Customer request',  hint: 'Receiver pushed delivery window' },
    { v: 'capacity',  label: 'Awaiting capacity', hint: 'No eligible carrier this wave' },
    { v: 'other',     label: 'Other',             hint: 'Free-text reason required' },
  ];
  const untilOptions = [
    { v: 'next-wave', label: 'Next wave', sub: '~1h' },
    { v: 'today',     label: 'End of day', sub: 'this wave + 4 more' },
    { v: 'manual',    label: 'Until manually released', sub: 'no auto re-plan' },
  ];

  const canConfirm = reason !== 'other' || note.trim().length > 0;

  return (
    <div className="modal__overlay" onClick={onCancel}>
      <div className="modal modal--narrow" onClick={(e) => e.stopPropagation()}>
        <div className="modal__head">
          <div className="modal__eyebrow">Hold trip · {trip.id}</div>
          <div className="modal__title">{trip.route.from} → {trip.route.to}</div>
          <div className="modal__sub">
            Status moves <span className="mono">{trip.status}</span> → <span className="mono" style={{ color: 'var(--amber-2)' }}>HELD</span>.
            Trip stays in the wave but is excluded from carrier tendering until released.
          </div>
        </div>

        <div className="modal__body">
          <div className="field">
            <label className="field__label">Reason</label>
            <div className="reason-list">
              {reasons.map(r => (
                <label key={r.v} className={`reason-list__opt ${reason === r.v ? 'selected' : ''}`}>
                  <input type="radio" name="hold-reason" checked={reason === r.v} onChange={() => setReason(r.v)} />
                  <span className="reason-list__main">
                    <span className="reason-list__lbl">{r.label}</span>
                    <span className="reason-list__hint">{r.hint}</span>
                  </span>
                </label>
              ))}
            </div>
          </div>

          <div className="field">
            <label className="field__label">Revisit when</label>
            <div className="seg seg--block">
              {untilOptions.map(o => (
                <button key={o.v} className={`seg__btn ${until === o.v ? 'on' : ''}`} onClick={() => setUntil(o.v)}>
                  <span style={{ display: 'block', fontWeight: 600 }}>{o.label}</span>
                  <span style={{ display: 'block', fontSize: 10, opacity: 0.7, marginTop: 1 }}>{o.sub}</span>
                </button>
              ))}
            </div>
          </div>

          <div className="field">
            <label className="field__label">Note <span style={{ color: 'var(--ink-3)', fontWeight: 400 }}>· {reason === 'other' ? 'required' : 'optional'}</span></label>
            <textarea className="textarea" rows="3"
              placeholder="Visible to Carrier Manager + audit log"
              value={note} onChange={e => setNote(e.target.value)} />
          </div>

          <AgentImpact text={
            <>
              Agent will: drop <span className="v">{trip.id}</span> from this wave's tender queue ·
              re-route pool orders if they have alternatives ·
              re-surface at <span className="v">{untilOptions.find(o => o.v === until)?.label.toLowerCase()}</span>.
            </>
          } />
        </div>

        <div className="modal__foot">
          <button className="btn" onClick={onCancel}>Cancel</button>
          <button className="btn btn--warning" disabled={!canConfirm}
            onClick={() => onConfirm({ reason, until, note })}>
            ⏸ Hold trip
          </button>
        </div>
      </div>
    </div>
  );
}

// ============================================================
// CancelModal — destructive; releases orders back to pool, fires
// downstream events. Requires reason + confirm checkbox.
// ============================================================
function CancelModal({ trip, onCancel, onConfirm }) {
  const [reason, setReason] = useTAState('infeasible');
  const [returnOrders, setReturnOrders] = useTAState(true);
  const [notifyCustomer, setNotifyCustomer] = useTAState(false);
  const [note, setNote]   = useTAState('');
  const [ack, setAck]     = useTAState(false);

  const invoice = trip.loadInvoice || 0;
  const orderCount = trip.orders.length;

  const reasons = [
    { v: 'infeasible',  label: 'Cannot be served',     hint: 'No fleet/carrier available' },
    { v: 'customer',    label: 'Customer cancelled',   hint: 'Order rescinded by receiver' },
    { v: 'consolidate', label: 'Consolidating',        hint: 'Moving to another trip' },
    { v: 'duplicate',   label: 'Duplicate / error',    hint: 'Created in error' },
  ];

  const canConfirm = ack && note.trim().length > 0;

  return (
    <div className="modal__overlay" onClick={onCancel}>
      <div className="modal modal--narrow modal--danger" onClick={(e) => e.stopPropagation()}>
        <div className="modal__head">
          <div className="modal__eyebrow modal__eyebrow--danger">⚠ Cancel trip · {trip.id}</div>
          <div className="modal__title">{trip.route.from} → {trip.route.to}</div>
          <div className="modal__sub">
            Status moves <span className="mono">{trip.status}</span> → <span className="mono" style={{ color: 'var(--red-2)' }}>CANCELLED</span>.
            This will release <span className="v">{orderCount}</span> order{orderCount === 1 ? '' : 's'} (${invoice.toLocaleString()} invoice value) and fire WMS/OMS reversal events.
          </div>
        </div>

        <div className="modal__body">
          <div className="cancel-impact">
            <div className="cancel-impact__row">
              <span className="cancel-impact__icon">↩</span>
              <span className="cancel-impact__text">Orders <b>back to pool</b> for next wave</span>
              <span className="cancel-impact__val">{orderCount} orders</span>
            </div>
            <div className="cancel-impact__row">
              <span className="cancel-impact__icon">$</span>
              <span className="cancel-impact__text">Invoice value affected</span>
              <span className="cancel-impact__val">${invoice.toLocaleString()}</span>
            </div>
            <div className="cancel-impact__row">
              <span className="cancel-impact__icon">⤓</span>
              <span className="cancel-impact__text">WMS pick list reversal</span>
              <span className="cancel-impact__val">auto</span>
            </div>
            <div className="cancel-impact__row">
              <span className="cancel-impact__icon">✉</span>
              <span className="cancel-impact__text">Customer notification</span>
              <span className="cancel-impact__val">{notifyCustomer ? 'on' : 'off'}</span>
            </div>
          </div>

          <div className="field">
            <label className="field__label">Reason</label>
            <div className="reason-list">
              {reasons.map(r => (
                <label key={r.v} className={`reason-list__opt ${reason === r.v ? 'selected' : ''}`}>
                  <input type="radio" name="cancel-reason" checked={reason === r.v} onChange={() => setReason(r.v)} />
                  <span className="reason-list__main">
                    <span className="reason-list__lbl">{r.label}</span>
                    <span className="reason-list__hint">{r.hint}</span>
                  </span>
                </label>
              ))}
            </div>
          </div>

          <div className="check-row">
            <label className="check-row__item">
              <input type="checkbox" checked={returnOrders} onChange={() => setReturnOrders(v => !v)} />
              <span>Return orders to pool (recommended)</span>
            </label>
            <label className="check-row__item">
              <input type="checkbox" checked={notifyCustomer} onChange={() => setNotifyCustomer(v => !v)} />
              <span>Notify customer of cancellation</span>
            </label>
          </div>

          <div className="field">
            <label className="field__label">Reason note <span style={{ color: 'var(--red-2)' }}>· required</span></label>
            <textarea className="textarea" rows="3"
              placeholder="Why are you cancelling? (audit + Carrier Manager review)"
              value={note} onChange={e => setNote(e.target.value)} />
          </div>

          <label className="ack-row">
            <input type="checkbox" checked={ack} onChange={() => setAck(v => !v)} />
            <span>I understand this is irreversible from this view and will fire downstream WMS/OMS events.</span>
          </label>
        </div>

        <div className="modal__foot">
          <button className="btn" onClick={onCancel}>Don't cancel</button>
          <button className="btn btn--danger" disabled={!canConfirm}
            onClick={() => onConfirm({ reason, returnOrders, notifyCustomer, note })}>
            ✕ Cancel trip
          </button>
        </div>
      </div>
    </div>
  );
}

// ============================================================
// SplitModal — interactive: pick orders to move to a new trip,
// see live utilization preview for both sides + recommendation.
// ============================================================
function SplitModal({ trip, onCancel, onConfirm }) {
  // Default split = agent recommendation (last order)
  const recommendedSplitIdx = Math.max(0, trip.orders.length - 1);
  const [moveSet, setMoveSet] = useTAState(new Set([trip.orders[recommendedSplitIdx].id]));
  const [carrier, setCarrier] = useTAState('same'); // same | new
  const [note, setNote]       = useTAState('');

  const toggle = (id) => {
    const next = new Set(moveSet);
    if (next.has(id)) next.delete(id); else next.add(id);
    setMoveSet(next);
  };

  // Compute the two resulting loads
  const remaining = trip.orders.filter(o => !moveSet.has(o.id));
  const moved     = trip.orders.filter(o =>  moveSet.has(o.id));

  const calc = (arr) => {
    const lbs = arr.reduce((a, o) => a + o.lbs, 0);
    const pal = arr.reduce((a, o) => a + o.pallets, 0);
    const inv = arr.reduce((a, o) => a + (o.invoiceValue || 0), 0);
    const util = Math.round((lbs / 45000) * 100);
    return { lbs, pal, inv, util };
  };
  const A = calc(remaining);
  const B = calc(moved);

  // Validation
  const errs = [];
  if (moved.length === 0) errs.push('Move at least one order to the new trip.');
  if (remaining.length === 0) errs.push('Keep at least one order on the original trip.');
  if (A.lbs > 45000) errs.push(`Trip A still overweight (${A.lbs.toLocaleString()} lbs).`);
  if (B.lbs > 45000) errs.push(`Trip B overweight (${B.lbs.toLocaleString()} lbs).`);

  const canConfirm = errs.length === 0;

  // synthetic IDs for the preview
  const aId = trip.id;
  const bId = trip.id + '-B';

  return (
    <div className="modal__overlay" onClick={onCancel}>
      <div className="modal modal--wide" onClick={(e) => e.stopPropagation()}>
        <div className="modal__head">
          <div className="modal__eyebrow">Split load · {trip.id}</div>
          <div className="modal__title">Create a second trip from selected orders</div>
          <div className="modal__sub">
            Selected orders will move to a new trip <span className="mono">{bId}</span> on the same lane.
            Agent will re-run feasibility for both after split.
          </div>
        </div>

        <div className="modal__body">
          {/* Preview cards */}
          <div className="split-preview">
            <SplitCard trip={trip} side="A" id={aId} orders={remaining} calc={A} />
            <div className="split-preview__arrow">→</div>
            <SplitCard trip={trip} side="B" id={bId} orders={moved} calc={B} isNew />
          </div>

          {/* Order picker */}
          <div className="split-picker">
            <div className="split-picker__head">
              <span>Pick orders to move to {bId}</span>
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10.5, color: 'var(--ink-3)' }}>
                AGENT REC: move ORD-{trip.orders[recommendedSplitIdx].id.replace('ORD-', '')}
              </span>
            </div>
            <div className="split-picker__list">
              {trip.orders.map(o => {
                const moving = moveSet.has(o.id);
                return (
                  <label key={o.id} className={`split-picker__row ${moving ? 'moving' : ''}`}>
                    <input type="checkbox" checked={moving} onChange={() => toggle(o.id)} />
                    <span className="split-picker__id">{o.id}</span>
                    <span className="split-picker__sku">{o.sku}</span>
                    <span className="split-picker__num">{o.pallets} pal</span>
                    <span className="split-picker__num">{o.lbs.toLocaleString()} lbs</span>
                    <span className="split-picker__num">${(o.invoiceValue || 0).toLocaleString()}</span>
                    <span className={`split-picker__arrow ${moving ? 'on' : ''}`}>{moving ? '→ B' : '↪ A'}</span>
                  </label>
                );
              })}
            </div>
          </div>

          <div className="field">
            <label className="field__label">Carrier for {bId}</label>
            <div className="seg seg--block">
              <button className={`seg__btn ${carrier === 'same' ? 'on' : ''}`} onClick={() => setCarrier('same')}>
                <span style={{ display: 'block', fontWeight: 600 }}>Same carrier</span>
                <span style={{ display: 'block', fontSize: 10, opacity: 0.7, marginTop: 1 }}>Reuse {trip.fleetLabel} tender</span>
              </button>
              <button className={`seg__btn ${carrier === 'new' ? 'on' : ''}`} onClick={() => setCarrier('new')}>
                <span style={{ display: 'block', fontWeight: 600 }}>Re-quote</span>
                <span style={{ display: 'block', fontSize: 10, opacity: 0.7, marginTop: 1 }}>Agent picks best fit for the smaller load</span>
              </button>
            </div>
          </div>

          <div className="field">
            <label className="field__label">Split note <span style={{ color: 'var(--ink-3)', fontWeight: 400 }}>· optional</span></label>
            <textarea className="textarea" rows="2"
              placeholder="Why are you splitting? (audit log)"
              value={note} onChange={e => setNote(e.target.value)} />
          </div>

          {errs.length > 0 && (
            <div className="split-errs">
              {errs.map((e, i) => <div key={i} className="split-errs__row">⚠ {e}</div>)}
            </div>
          )}

          <AgentImpact text={
            <>
              Agent will: create <span className="v">{bId}</span> · move <span className="v">{moved.length}</span> order{moved.length === 1 ? '' : 's'} ·
              re-run feasibility on both · refresh fleet recommendations · log split to audit trail.
            </>
          } />
        </div>

        <div className="modal__foot">
          <button className="btn" onClick={onCancel}>Cancel</button>
          <button className="btn btn--primary" disabled={!canConfirm}
            onClick={() => onConfirm({
              keep: remaining.map(o => o.id),
              move: moved.map(o => o.id),
              newTripId: bId, carrier, note,
            })}>
            ⊟ Split into {aId} + {bId}
          </button>
        </div>
      </div>
    </div>
  );
}

function SplitCard({ id, orders, calc, isNew }) {
  const utilKind = calc.util > 100 ? 'red' : calc.util > 95 ? 'amber' : calc.util < 50 ? 'amber' : 'green';
  return (
    <div className={`split-card ${isNew ? 'split-card--new' : ''}`}>
      <div className="split-card__head">
        <span className="split-card__id">{id}{isNew && <span className="pill pill--purple" style={{ marginLeft: 6, fontSize: 9 }}>NEW</span>}</span>
        <span className="split-card__count">{orders.length} order{orders.length === 1 ? '' : 's'}</span>
      </div>
      <div className="split-card__util">
        <div className="split-card__util-num">
          <span className={`split-card__util-val util-${utilKind}`}>{calc.util}%</span>
          <span className="split-card__util-lbl">util</span>
        </div>
        <div className="split-card__bar">
          <div className={`split-card__bar-fill util-fill-${utilKind}`}
               style={{ width: `${Math.min(calc.util, 100)}%` }} />
          <div className="split-card__bar-tick" style={{ left: '80%' }} title="80% threshold" />
        </div>
      </div>
      <div className="split-card__stats">
        <span><span className="lbl">Weight</span><span className="val">{calc.lbs.toLocaleString()} lbs</span></span>
        <span><span className="lbl">Pallets</span><span className="val">{calc.pal}</span></span>
        <span><span className="lbl">Invoice</span><span className="val">${calc.inv.toLocaleString()}</span></span>
      </div>
      <div className="split-card__orders">
        {orders.length === 0 && <span className="split-card__empty">(no orders)</span>}
        {orders.map(o => (
          <span key={o.id} className="split-card__pill">{o.id} · {o.pallets}p</span>
        ))}
      </div>
    </div>
  );
}

function AgentImpact({ text }) {
  return (
    <div className="agent-impact">
      <span className="agent-impact__icon">TP</span>
      <span><span className="agent-impact__label">Agent will:</span> {text}</span>
    </div>
  );
}

Object.assign(window, { HoldModal, CancelModal, SplitModal });
