/* Pantalla 4 — Detalle de orden + DAG de operaciones */

// node positions (Dagre-style LR layout, precomputed)
const NW = 168, AY = 30;
const POS = {
  c1: { x: 24,   y: 58  }, c2: { x: 230,  y: 58  }, c3: { x: 436,  y: 58  },
  m1: { x: 24,   y: 218 }, m2: { x: 436,  y: 218 },
  a1: { x: 642,  y: 326 }, a2: { x: 848,  y: 326 }, a3: { x: 1054, y: 326 },
  a4: { x: 1260, y: 326 }, a5: { x: 1466, y: 326 },
};
const CONSUME_EDGES = { 'c3>a2': 1, 'm2>a3': 1 };

function DagView() {
  function path([a, b]) {
    const p = POS[a], q = POS[b];
    const x1 = p.x + NW, y1 = p.y + AY, x2 = q.x, y2 = q.y + AY;
    const consume = CONSUME_EDGES[a + '>' + b];
    if (y1 === y2) {
      const mx = (x1 + x2) / 2;
      return { d: `M${x1},${y1} C${mx},${y1} ${mx},${y2} ${x2},${y2}`, consume };
    }
    const cx = x1 + (x2 - x1) * 0.5;
    return { d: `M${x1},${y1} C${cx},${y1} ${cx},${y2} ${x2},${y2}`, consume };
  }
  const lanes = [
    { lbl: 'Pieza · Cuello', x: 8,   y: 32,  w: 620,  h: 150 },
    { lbl: 'Pieza · Manga',  x: 8,   y: 192, w: 620,  h: 130 },
    { lbl: 'Ensamble',       x: 636, y: 300, w: 1030, h: 150 },
  ];
  return (
    <div className="dag-wrap">
      <div className="dag-canvas" style={{ width: 1660, height: 470 }}>
        <svg className="dag-svg" viewBox="0 0 1660 470">
          <defs>
            <marker id="ah" markerWidth="7" markerHeight="7" refX="5.5" refY="3" orient="auto">
              <path d="M0,0 L6,3 L0,6 Z" fill="#9aa893" />
            </marker>
            <marker id="ahc" markerWidth="7" markerHeight="7" refX="5.5" refY="3" orient="auto">
              <path d="M0,0 L6,3 L0,6 Z" fill="#4c6b8b" />
            </marker>
          </defs>
          {window.EDGES.map((e, i) => {
            const { d, consume } = path(e);
            return <path key={i} d={d} fill="none"
              stroke={consume ? '#4c6b8b' : '#9aa893'} strokeWidth={consume ? 2 : 1.5}
              strokeDasharray={consume ? '5 4' : 'none'}
              markerEnd={consume ? 'url(#ahc)' : 'url(#ah)'} />;
          })}
        </svg>
        {lanes.map((l, i) => (
          <div className="dag-lane" key={i} style={{ left: l.x, top: l.y, width: l.w, height: l.h }}>
            <span className="lbl">{l.lbl}</span>
          </div>
        ))}
        {window.OPS.map((op) => {
          const p = POS[op.id];
          return (
            <div className={`node${op.fin ? ' fin' : ''}`} key={op.id} style={{ left: p.x, top: p.y }}>
              <div className="nh">
                <div className="nn">{op.name}</div>
                <span className={`dot ${op.dot}`}></span>
              </div>
              <div className="nmeta"><span>{op.mach}</span><span>·</span><span>SAM {op.sam}</span></div>
              {op.status === 'nt'
                ? <div style={{ marginTop: 8 }}><Pill kind="wt">Pendiente</Pill></div>
                : <div className="nbar"><div className="prog" style={{ minWidth: 0 }}>
                    <div className="bar"><i className={op.bar} style={{ width: op.pct + '%' }}></i></div>
                    <span className="pct">{op.pct}%</span></div></div>}
              {op.fin && <span className="finbadge">FINALIZADORA</span>}
              {op.consumes && <span className="consumes">consume · {op.consumes}</span>}
            </div>
          );
        })}
      </div>
    </div>
  );
}

function OpsTable() {
  return (
    <div className="twrap">
      <table className="dt">
        <thead>
          <tr>
            <th className="c-chk"><span className="chk"></span></th>
            <th className="c-num"></th>
            <th>Operación</th><th>Pieza</th><th>Avance</th><th>SAM</th>
            <th>Máquina</th><th>Estado</th><th>Señal</th>
          </tr>
        </thead>
        <tbody>
          {window.OPS.map((op, i) => {
            const stMap = { ok: ['ok', 'Listo'], cl: ['cl', 'En curso'], wn: ['wn', 'En riesgo'], ct: ['ct', 'Crítico'], nt: ['wt', 'Pendiente'] };
            const sigMap = { ok: ['ok', 'Flujo normal'], wn: ['wn', 'Stock bajo · 30/50'], ct: ['ct', 'Frena en ~40 min'], cl: [null, ''], nt: ['nt', 'Bloqueado'] };
            const st = stMap[op.status], sg = sigMap[op.status];
            return (
              <tr key={op.id}>
                <td className="c-chk"><span className="chk"></span></td>
                <td className="c-num">{i + 1}</td>
                <td><div className="namecell">
                  <Tile mono={op.name.slice(0, 2)} kind={op.fin ? 'cl' : ''} />
                  <span className="nm">{op.name}{op.fin && <small className="mono">finalizadora</small>}</span>
                </div></td>
                <td className="muted">{op.piece}</td>
                <td>{op.status === 'nt' ? <span style={{ color: 'var(--stone)' }}>—</span> : <ProgressBar pct={op.pct} kind={op.bar} />}</td>
                <td className="muted m">{op.sam}</td>
                <td className="muted m">{op.mach}</td>
                <td><Pill kind={st[0]}>{st[1]}</Pill></td>
                <td><Signal kind={sg[0]}>{sg[1]}</Signal></td>
              </tr>
            );
          })}
        </tbody>
      </table>
      <div className="tfade"></div>
    </div>
  );
}

function OrderDetail({ order, onBack, onClose }) {
  const [tab, setTab] = React.useState('dag');
  const o = order || window.ORDERS[0];
  return (
    <div className="panel fade-in">
      <TopBar onBack={onBack} onClose={onClose}
        crumb={<div className="crumb"><b className="mono">{o.op}</b><span className="sep">·</span>{o.gar}<span className="sep">·</span>{o.cli}</div>} />

      <div className="head">
        <div>
          <div className="page-h1">{o.gar}</div>
          <div className="page-sub mono">{o.op} · Entrega {o.delivery} · {o.days} días restantes · {o.units} uds</div>
        </div>
        <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
          <Pill kind={o.status[0]}>{o.status[1]}</Pill>
          <div className="live"><span className="pulse"></span>EN VIVO</div>
        </div>
      </div>

      <div className="meta-strip">
        <div className="cell"><div className="k">Cliente</div><div className="v">{o.cli}</div></div>
        <div className="cell"><div className="k">Planta</div><div className="v"><Icon name="pin" style={{ width: 14, height: 14, strokeWidth: 1.8, stroke: 'var(--stone)' }} />{o.plant}</div></div>
        <div className="cell"><div className="k">Total</div><div className="v"><span className="mono">560</span> uds</div></div>
        <div className="cell"><div className="k">Tallas</div><div className="v"><div className="chiprow">
          {['S', 'M', 'L', 'XL'].map((s) => <span className="szchip" key={s}>{s}</span>)}
        </div></div></div>
        <div className="cell"><div className="k">Variantes</div><div className="v"><div className="chiprow">
          <span className="varchip"><span className="sw" style={{ background: '#3A5BA8' }}></span>Azul · 330</span>
          <span className="varchip"><span className="sw" style={{ background: '#B23A48' }}></span>Roja · 230</span>
        </div></div></div>
      </div>

      <div className="bar-row" style={{ marginTop: 12 }}>
        <div className="tabs">
          <div className={`tab${tab === 'dag' ? ' on' : ''}`} onClick={() => setTab('dag')}><Icon name="flow" />Flujo (DAG)</div>
          <div className={`tab${tab === 'ops' ? ' on' : ''}`} onClick={() => setTab('ops')}><Icon name="rows" />Operaciones <span className="ct">10</span></div>
          <div className="tab"><Icon name="swatch" />Variantes</div>
          <div className="tab"><Icon name="pkg" />Marcaciones</div>
        </div>
        <div className="tools">
          <div className="tool"><Icon name="plus" /><span>Marcar producción</span></div>
        </div>
      </div>

      {tab === 'dag' ? <DagView /> : <OpsTable />}
    </div>
  );
}

Object.assign(window, { OrderDetail });
