/* global React */
/* Operations — shipment master-detail */

window.OperationsScreen = function OperationsScreen() {
  const [selectedId, setSelectedId] = React.useState('SHP-104822');
  const shipments = window.SHIPMENTS;
  const selected = shipments.find(s => s.id === selectedId);
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '440px 1fr', height: '100%', minHeight: 0 }}>
      {/* Master list */}
      <div style={{ borderRight: '1px solid var(--n-100)', background: 'var(--bg-surface)', display: 'flex', flexDirection: 'column', minHeight: 0 }}>
        <div style={{ padding: '16px 20px', borderBottom: '1px solid var(--n-100)' }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <div>
              <div style={{ fontSize: 16, fontWeight: 600 }}>Operations</div>
              <div style={{ fontSize: 11.5, color: 'var(--fg-3)', marginTop: 2 }}>{shipments.length} active shipments · 12 in transit</div>
            </div>
            <button className="btn btn-sm btn-secondary"><window.Icon name="filter" size={11}/></button>
          </div>
          <div style={{ display: 'flex', gap: 6, marginTop: 12, flexWrap: 'wrap' }}>
            {['All', 'In transit', 'Pickup', 'At port', 'Delivered'].map((c, i) => (
              <button key={i} className={`chip ${i === 0 ? 'active' : ''}`}>{c}</button>
            ))}
          </div>
        </div>
        <div style={{ flex: 1, overflow: 'auto' }}>
          {shipments.map(s => (
            <div key={s.id}
                 onClick={() => setSelectedId(s.id)}
                 style={{
                   padding: '12px 20px',
                   borderBottom: '1px solid var(--n-75)',
                   cursor: 'pointer',
                   background: s.id === selectedId ? 'var(--brand-50)' : 'transparent',
                   borderLeft: s.id === selectedId ? '3px solid var(--brand-600)' : '3px solid transparent',
                 }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <span className="mono" style={{ fontSize: 11.5, fontWeight: 600, color: 'var(--fg-2)' }}>{s.id}</span>
                <span style={{ fontSize: 10.5, color: 'var(--fg-4)' }}>ETA {s.eta}</span>
              </div>
              <div style={{ fontSize: 13, fontWeight: 600, marginTop: 4 }}>{s.customer}</div>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 4 }}>
                <window.Route origin={s.origin} dest={s.destination} mode={s.mode} compact/>
                <span className="badge b-blue" style={{ fontSize: 10.5 }}>{s.stage}</span>
              </div>
              <div style={{ marginTop: 8 }}>
                <StageBar stage={s.stageIdx}/>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Detail */}
      <div style={{ overflow: 'auto', minHeight: 0 }}>
        {selected ? <ShipmentDetail s={selected}/> : null}
      </div>
    </div>
  );
};

function StageBar({ stage }) {
  return (
    <div style={{ display: 'flex', gap: 3 }}>
      {Array.from({ length: 7 }).map((_, i) => (
        <div key={i} style={{
          flex: 1, height: 4, borderRadius: 2,
          background: i <= stage ? 'var(--brand-600)' : 'var(--n-100)',
        }}/>
      ))}
    </div>
  );
}

function ShipmentDetail({ s }) {
  return (
    <div style={{ padding: 24, display: 'flex', flexDirection: 'column', gap: 16, maxWidth: 1040 }}>
      {/* Header */}
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between' }}>
        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
            <span className="mono" style={{ fontSize: 12, color: 'var(--fg-3)' }}>{s.id}</span>
            <span className="badge b-blue">{s.stage}</span>
            <span style={{ fontSize: 11.5, color: 'var(--fg-3)' }}>· From {s.rfqId}</span>
          </div>
          <div style={{ fontSize: 22, fontWeight: 600 }}>{s.customer}</div>
          <div style={{ fontSize: 13, color: 'var(--fg-3)', marginTop: 4, display: 'flex', alignItems: 'center', gap: 12 }}>
            <window.Route origin={s.origin} dest={s.destination} mode={s.mode}/>
            <span>·</span>
            <span>{s.carrier} · {s.containerType}</span>
            <span>·</span>
            <span>ETA <strong style={{ color: 'var(--fg-1)' }}>{s.eta}</strong></span>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 6 }}>
          <button className="btn btn-sm btn-secondary"><window.Icon name="map" size={12}/> Track</button>
          <button className="btn btn-sm btn-secondary"><window.Icon name="mail-out" size={12}/> Email customer</button>
        </div>
      </div>

      {/* Stage tracker */}
      <div className="card" style={{ padding: 18 }}>
        <Stepper stages={s.stages} currentIdx={s.stageIdx}/>
      </div>

      {/* Two columns: Documents | Shipment object */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 16 }}>
        <DocumentsCard docs={s.docs} extracting={s.extracting}/>
        <ShipmentObjectCard fields={s.shipmentObject}/>
      </div>

      {/* Communications log */}
      <CommunicationsCard comms={s.comms}/>
    </div>
  );
}

function Stepper({ stages, currentIdx }) {
  return (
    <div style={{ position: 'relative' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', position: 'relative' }}>
        <div style={{ position: 'absolute', top: 12, left: 12, right: 12, height: 2, background: 'var(--n-100)' }}/>
        <div style={{ position: 'absolute', top: 12, left: 12, height: 2, background: 'var(--brand-600)', width: `calc(${(currentIdx / (stages.length - 1)) * 100}% - 12px)`, maxWidth: 'calc(100% - 24px)' }}/>
        {stages.map((st, i) => {
          const done = i < currentIdx, current = i === currentIdx, future = i > currentIdx;
          return (
            <div key={i} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', flex: 1, position: 'relative', zIndex: 1, minWidth: 0 }}>
              <div style={{
                width: 24, height: 24, borderRadius: '50%',
                background: future ? 'white' : 'var(--brand-600)',
                border: `2px solid ${future ? 'var(--n-200)' : 'var(--brand-600)'}`,
                color: future ? 'var(--fg-4)' : 'white',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 11, fontWeight: 700,
                boxShadow: current ? '0 0 0 4px var(--brand-50)' : 'none',
              }}>
                {done ? <window.Icon name="check" size={12}/> : i + 1}
              </div>
              <div style={{ marginTop: 8, fontSize: 11, fontWeight: current ? 700 : 600, color: future ? 'var(--fg-4)' : 'var(--fg-1)', textAlign: 'center', minWidth: 0 }}>
                {st.name}
              </div>
              <div style={{ fontSize: 10, color: 'var(--fg-4)', marginTop: 2 }}>{st.ts || ''}</div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function DocumentsCard({ docs, extracting }) {
  return (
    <div className="card" style={{ padding: 18 }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
        <div style={{ fontSize: 13.5, fontWeight: 600 }}>Documents</div>
        <span style={{ fontSize: 11.5, color: 'var(--fg-3)' }}>{docs.filter(d => d.status === 'Verified' || d.status === 'Extracted').length} of {docs.length} complete</span>
      </div>

      {/* Dropzone */}
      <div style={{
        border: '1px dashed var(--n-200)', borderRadius: 8, padding: 14,
        textAlign: 'center', background: 'var(--n-25)',
        display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, marginBottom: 12,
        fontSize: 12, color: 'var(--fg-3)',
      }}>
        <window.Icon name="upload" size={14}/>
        <span>Drop documents here · agent will extract fields automatically</span>
      </div>

      {/* Doc rows */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        {docs.map((d, i) => (
          <div key={i} style={{
            display: 'grid', gridTemplateColumns: '24px 1fr 110px 90px',
            alignItems: 'center', gap: 10, padding: '10px 12px',
            border: '1px solid var(--n-100)', borderRadius: 8,
            background: d.status === 'Pending' ? 'var(--n-25)' : 'white',
          }}>
            <window.Icon name="doc" size={16} color={d.status === 'Pending' ? '#98A2B3' : '#1659CB'}/>
            <div>
              <div style={{ fontSize: 12.5, fontWeight: 600 }}>{d.type}</div>
              <div style={{ fontSize: 10.5, color: 'var(--fg-4)', marginTop: 1 }}>
                {d.uploader ? `${d.uploader} · ${d.ts}` : 'Awaiting upload'}
              </div>
            </div>
            <span className={`badge ${
              d.status === 'Verified' ? 'b-success' :
              d.status === 'Extracted' ? 'b-blue' :
              d.status === 'Uploaded' ? 'b-warning' :
              'b-neutral'
            }`} style={{ fontSize: 10.5, justifySelf: 'flex-start' }}>{d.status}</span>
            <button className="btn btn-sm btn-ghost" style={{ justifySelf: 'flex-end' }}>{d.status === 'Pending' ? 'Upload' : 'View'}</button>
          </div>
        ))}
      </div>

      {/* Live extraction (agent thinking) */}
      {extracting && (
        <div style={{ marginTop: 14, padding: 14, background: 'var(--agent-50)', border: '1px solid var(--agent-200)', borderRadius: 8 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
            <span className="agent-chip"><span className="agent-dot pulse"/>Agent extracting…</span>
            <span style={{ fontSize: 11.5, color: 'var(--agent-700)' }}>Bill of Lading · MAEU-{Math.floor(8200000 + Math.random() * 999)}</span>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 8 }}>
            {extracting.fields.map((f, i) => (
              <ExtractingField key={i} {...f} delay={i * 240}/>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

function ExtractingField({ label, value, confidence, delay = 0 }) {
  const [done, setDone] = React.useState(false);
  React.useEffect(() => {
    const t = setTimeout(() => setDone(true), delay + 400);
    return () => clearTimeout(t);
  }, [delay]);
  const color = confidence > 0.95 ? '#12B76A' : confidence > 0.85 ? '#F79009' : '#D40B00';
  return (
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      padding: '6px 10px', background: 'white', borderRadius: 6, border: `1px solid ${done ? 'var(--n-100)' : 'var(--agent-200)'}`,
      opacity: done ? 1 : 0.6,
      transition: 'opacity 0.3s ease',
    }}>
      <div style={{ minWidth: 0 }}>
        <div style={{ fontSize: 10.5, color: 'var(--fg-3)' }}>{label}</div>
        <div style={{ fontSize: 12, fontWeight: 600, marginTop: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }} className={typeof value === 'string' && /^[A-Z0-9-]+$/.test(value) ? 'mono' : ''}>
          {done ? value : '···'}
        </div>
      </div>
      {done && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 4, marginLeft: 8, flexShrink: 0 }}>
          <span style={{ width: 6, height: 6, borderRadius: 50, background: color }}/>
          <span className="mono" style={{ fontSize: 10, color: 'var(--fg-3)' }}>{Math.round(confidence * 100)}%</span>
        </div>
      )}
    </div>
  );
}

function ShipmentObjectCard({ fields }) {
  return (
    <div className="card" style={{ padding: 18 }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
        <div style={{ fontSize: 13.5, fontWeight: 600 }}>Shipment object</div>
        <span style={{ fontSize: 11, color: 'var(--fg-3)' }}>{fields.length} fields</span>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column' }}>
        {fields.map((f, i) => (
          <div key={i} style={{
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            padding: '8px 0',
            borderBottom: i < fields.length - 1 ? '1px solid var(--n-75)' : 'none',
          }}>
            <div style={{ display: 'flex', flexDirection: 'column', minWidth: 0 }}>
              <span style={{ fontSize: 11.5, color: 'var(--fg-3)' }}>{f.label}</span>
              <span style={{ fontSize: 12.5, fontWeight: 600, marginTop: 1 }} className={f.mono ? 'mono' : ''}>{f.value}</span>
            </div>
            {f.source && (
              <span className="badge b-neutral" style={{ fontSize: 10, marginLeft: 8 }}>
                <window.Icon name="doc" size={9}/> {f.source}
              </span>
            )}
          </div>
        ))}
      </div>
    </div>
  );
}

function CommunicationsCard({ comms }) {
  return (
    <div className="card" style={{ padding: 18 }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
        <div style={{ fontSize: 13.5, fontWeight: 600 }}>Communications log</div>
        <button className="btn btn-sm btn-ghost"><window.Icon name="filter" size={11}/> All channels</button>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {comms.map((c, i) => (
          <div key={i} style={{ display: 'flex', gap: 12, padding: '10px 0', borderBottom: i < comms.length - 1 ? '1px solid var(--n-75)' : 'none' }}>
            <div style={{
              width: 28, height: 28, borderRadius: 50, flexShrink: 0,
              background: c.byAgent ? 'var(--agent-50)' : 'var(--brand-50)',
              color: c.byAgent ? 'var(--agent-700)' : 'var(--brand-700)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <window.Icon name={c.byAgent ? 'sparkles' : c.dir === 'out' ? 'mail-out' : 'mail-in'} size={13}/>
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 2 }}>
                <span style={{ fontSize: 12.5, fontWeight: 600 }}>{c.from}</span>
                <span style={{ fontSize: 11, color: 'var(--fg-4)' }}>→</span>
                <span style={{ fontSize: 12, color: 'var(--fg-3)' }}>{c.to}</span>
                <div style={{ flex: 1 }}/>
                <span style={{ fontSize: 10.5, color: 'var(--fg-4)' }}>{c.ts}</span>
              </div>
              <div style={{ fontSize: 12, color: 'var(--fg-2)' }}>{c.subject}</div>
              {c.summary && <div style={{ fontSize: 11.5, color: 'var(--fg-3)', marginTop: 4 }}>{c.summary}</div>}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
