/* ══════════════════════════════════════════════════
   MOCKUPS — didactic illustrations of the platform.

   These are NOT screens of the system. Each one shows a single idea,
   so a first-time visitor gets the benefit in a few seconds:
   • FleetMapMock    where every courier is, on which route
   • ProofMock       the result of one aviso and its evidence
   • AvisoBoardMock  avisos grouped by status and result
   • RoutingMock     scattered deliveries become one ordered route
   • PrintMock       the sheets ready to print, in route order
   • ProvokeMap      question marks that become couriers on a map

   All data is fictional: companies, addresses and protocols are
   invented, and no real person ever appears here.

   Color has one meaning everywhere: green = entregue, red = negativa,
   violet = other occurrence, amber = waiting, blue = on the way.
   Crimson marks the action or the route.

   Every map shares one street grid (MAP_*).
══════════════════════════════════════════════════ */

/* ── Shared fictional data ─────────────────────────── */
/* `stop` = position in the planned route. Array order = order received. */
const ROUTE_AVISOS = [
  { prot:'00409', dest:'Vértice Contabilidade',   addr:'Av. Rebouças, 2.310',         stop:3 },
  { prot:'00415', dest:'Nova Era Serviços',       addr:'Al. Santos, 1.890',           stop:5 },
  { prot:'00418', dest:'Comercial Aurora Ltda',   addr:'R. dos Pinheiros, 870',       stop:1 },
  { prot:'00422', dest:'Studio Lume Arquitetura', addr:'R. Fradique Coutinho, 1.120', stop:2 },
  { prot:'00427', dest:'Horizonte Imóveis',       addr:'R. Augusta, 2.040',           stop:6 },
  { prot:'00431', dest:'Grupo Atlas Comércio',    addr:'R. Oscar Freire, 455',        stop:4 },
];
const AVISOS_BY_STOP = [...ROUTE_AVISOS].sort((a, b) => a.stop - b.stop);
const pad2 = n => String(n).padStart(2, '0');

const StopBadge = ({ n, dim }) => (
  <span className={`stop-badge ${dim ? 'is-dim' : ''}`}>{n == null ? '–' : pad2(n)}</span>
);

/* A soft stage with one simple card: a title and one optional control. */
const UIFrame = ({ title, meta, right, className = '', children }) => (
  <div className={`ui-stage ${className}`}>
    <div className="ui-frame">
      <div className="ui-head">
        <div className="ui-title"><strong>{title}</strong>{meta && <span>{meta}</span>}</div>
        {right && <div className="ui-head-right">{right}</div>}
      </div>
      <div className="ui-body">{children}</div>
    </div>
  </div>
);

/* ── Street grid ───────────────────────────────────── */
const MAP_W = 560, MAP_H = 430;
const MAP_XS = [40, 120, 200, 280, 360, 440, 520];
const MAP_YS = [40, 110, 180, 250, 320, 390];
const MAP_BASE = { x:40, y:390 };
/* Stop coordinates, indexed by stop number (1-based). */
const MAP_STOPS = [null, [120,320], [200,250], [280,320], [360,250], [440,180], [360,110]];
/* The planned route follows the streets (orthogonal segments only). */
const ROUTE_D = 'M40 390 H120 V320 H200 V250 H280 V320 H360 V250 H440 V180 V110 H360';
/* The same stops in arrival order: straight lines that cross each other. */
const RAW_D = 'M40 390 ' + ROUTE_AVISOS.map(a => `L${MAP_STOPS[a.stop][0]} ${MAP_STOPS[a.stop][1]}`).join(' ');

/* Map colors come from CSS classes (var() is illegal in SVG attributes). */
const MapBase = () => {
  const blocks = [];
  const xs = [-40, ...MAP_XS], ys = [-30, ...MAP_YS];
  for (let i = 0; i < xs.length; i++) {
    for (let j = 0; j < ys.length; j++) {
      const park = (i === 5 && j === 4) || (i === 2 && j === 1);
      blocks.push(<rect key={`${i}-${j}`} x={xs[i] + 8} y={ys[j] + 8} width={64} height={54} rx={4}
                        className={park ? 'mb-park' : 'mb-block'}/>);
    }
  }
  return <g><rect width={MAP_W} height={MAP_H} className="mb-bg"/>{blocks}</g>;
};

/* Position lives on the outer <g> attribute; the CSS pop animation runs
   on the inner one (a CSS transform would override the attribute). */
const MapPin = ({ n, x, y, state = 'route', delay = 0 }) => (
  <g transform={`translate(${x} ${y})`}>
    <g className={`map-pin is-${state}`} style={{ '--d': `${delay}ms` }}>
      <circle r="17" className="map-pin-halo"/>
      <circle r="12" className="map-pin-dot"/>
      {state !== 'raw' && <text y="4.5" textAnchor="middle" className="map-pin-n">{n}</text>}
    </g>
  </g>
);

const MapDepot = () => (
  <g transform={`translate(${MAP_BASE.x} ${MAP_BASE.y})`}>
    <circle r="9" className="map-depot"/>
    <circle r="3.5" fill="#fff"/>
  </g>
);

/* ══════════════ 01 · FROTA — every courier on one map ══════════════
   Three routes, three colors, a card per courier below the map.
   `from` is where the courier marker sits; `leg` is what it drives while
   on screen. animateMotion runs only while the map is watchable. */
const FLEET = [
  { id:'01', tone:'brand', route:'Rota A', done:3, total:5, from:[200,250],
    d:'M40 390 H120 V320 H200 V250 H280 V180', driven:'M40 390 H120 V320 H200 V250', leg:'M200 250 H280',
    stops:[[120,390,1],[120,320,1],[200,320,1],[280,250,0],[280,180,0]] },
  { id:'02', tone:'blue', route:'Rota B', done:2, total:5, from:[120,180],
    d:'M40 390 V180 H120 V40 H280', driven:'M40 390 V180 H120', leg:'M120 180 V110',
    stops:[[40,250,1],[40,180,1],[120,110,0],[120,40,0],[280,40,0]] },
  { id:'03', tone:'violet', route:'Rota C', done:4, total:7, from:[440,320],
    d:'M120 390 H360 V320 H440 V180 H520 V110', driven:'M120 390 H360 V320 H440', leg:'M440 320 V250',
    stops:[[280,390,1],[360,390,1],[360,320,1],[400,320,1],[440,250,0],[440,180,0],[520,110,0]] },
];

const FleetMapMock = ({ active }) => {
  const moving = active && !REDUCED_MOTION;
  return (
    <div className="ui-stage fleet-ui">
      <div className="fleet-map">
        <svg viewBox={`0 0 ${MAP_W} ${MAP_H}`} preserveAspectRatio="xMidYMid slice" role="img"
             aria-label="Mapa com três entregadores em rota, cada um com sua rota colorida e as entregas concluídas marcadas em verde">
          <MapBase/>
          {FLEET.map(f => (
            <g key={f.id} className={`tone-${f.tone}`}>
              <path d={f.d} className="fleet-plan"/>
              <path d={f.driven} className="fleet-driven"/>
            </g>
          ))}
          <MapDepot/>
          {FLEET.map(f => (
            <g key={f.id} className={`tone-${f.tone}`}>
              {f.stops.map(([x, y, done]) => (
                <g key={`${x}-${y}`} transform={`translate(${x} ${y})`}>
                  <circle r="8" className={done ? 'fleet-stop-done' : 'fleet-stop'}/>
                  {done === 1 && <path d="M-3.4 .3 L-1 2.7 L3.5 -2.3" fill="none" stroke="#fff" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round"/>}
                </g>
              ))}
              <g transform={moving ? undefined : `translate(${f.from[0]} ${f.from[1]})`}>
                {moving && <animateMotion dur="6s" repeatCount="indefinite" path={f.leg}/>}
                <circle r="21" className="fleet-me-halo"/>
                <circle r="15" className="fleet-me-dot"/>
                <text y="4.4" textAnchor="middle" className="fleet-me-n">{f.id}</text>
              </g>
            </g>
          ))}
        </svg>
        <span className="fleet-live"><span className="live-dot"/>Frota ao vivo</span>
      </div>
      <ul className="fleet-cards">
        {FLEET.map(f => (
          <li key={f.id} className={`tone-${f.tone}`}>
            <span className="fleet-card-n">{f.id}</span>
            <div>
              <strong>{f.route}</strong>
              <span className="fleet-bar" aria-hidden="true"><i style={{ width:`${f.done / f.total * 100}%` }}/></span>
              <em>{f.done} de {f.total} <span className="fleet-unit">entregues</span></em>
            </div>
          </li>
        ))}
      </ul>
    </div>
  );
};

/* ══════════════ 01 · COMPROVAÇÃO — one aviso, one clear result ══════════════
   The toggle swaps the outcome: green check or red X, then the evidence. */
const IPen = ({ sz }) => <Ico sz={sz}><path d="M3 17c3-5 5-9 7-9s-1 8 1 8 2-4 4-4 1 3 3 3 2-1 3-1"/><line x1="3" y1="21" x2="21" y2="21"/></Ico>;

const PROOF = {
  entregue: {
    tone:'green', label:'Entregue', note:'Aviso assinado no recebimento', icon:<ICheck sz={26} stroke={3}/>,
    rows:[[ICamera,'Foto','Anexada'], [IPen,'Assinatura','Registrada'], [IClock,'Horário','Hoje, 08:31'], [IPin,'Local','Confere com o endereço']],
  },
  negativa: {
    tone:'red', label:'Negativa', note:'Entrega não realizada', icon:<IClose sz={26} stroke={3}/>,
    rows:[[IDoc,'Motivo','Destinatário ausente'], [ICamera,'Foto','Anexada'], [IClock,'Horário','Hoje, 09:12'], [IPin,'Local','Confere com o endereço']],
  },
};

const ProofMock = () => {
  const [kind, setKind] = useState('entregue');
  const p = PROOF[kind];
  return (
    <div className="proof">
      <div className="ui-seg" role="group" aria-label="Ver exemplo de resultado">
        {Object.keys(PROOF).map(k => (
          <button key={k} type="button" className={kind === k ? 'is-on' : ''} aria-pressed={kind === k}
                  data-track="proof_toggle" data-track-label={k} onClick={() => setKind(k)}>{PROOF[k].label}</button>
        ))}
      </div>
      <div className="proof-card" key={kind}>
        <div className={`proof-result tone-${p.tone}`}>
          <span className="proof-ic">{p.icon}</span>
          <div><strong>{p.label}</strong><em>{p.note}</em></div>
        </div>
        <ul className="proof-rows">
          {p.rows.map(([I, t, v]) => <li key={t}><I sz={16}/><span>{t}</span><b>{v}</b></li>)}
        </ul>
      </div>
    </div>
  );
};

/* ══════════════ 02 · GESTÃO DOS AVISOS — cards by status ══════════════
   Four columns read left to right as the life of an aviso. */
const AVISO_BOARD = [
  { key:'aguardando', title:'A entregar', tone:'amber', I:IDoc, count:3, cards:[
    { dest:'Horizonte Imóveis', prot:'00427' }, { dest:'Grupo Atlas Comércio', prot:'00431' } ] },
  { key:'emrota', title:'Em rota', tone:'blue', I:IRoute, count:2, cards:[
    { dest:'Vértice Contabilidade', prot:'00409' }, { dest:'Nova Era Serviços', prot:'00415' } ] },
  { key:'entregues', title:'Entregues', tone:'green', I:ICheck, count:4, cards:[
    { dest:'Comercial Aurora Ltda', prot:'00418', tag:'Assinado às 08:31' }, { dest:'Studio Lume Arquitetura', prot:'00422', tag:'Assinado às 08:58' } ] },
  { key:'negativa', title:'Negativa e ocorrências', tone:'red', I:IClose, count:2, cards:[
    { dest:'Prisma Odontologia', prot:'00436', tag:'Negativa: recusou assinar' }, { dest:'Casa Norte Comércio', prot:'00440', tag:'Ocorrência: ausente', tagTone:'violet' } ] },
];

const AvisoBoardMock = () => (
  <div className="ui-stage board-ui">
    <div className="board">
      {AVISO_BOARD.map(c => (
        <section key={c.key} className={`board-col tone-${c.tone}`} aria-label={`${c.title}: ${c.count} avisos`}>
          <header><span className="board-ic"><c.I sz={15} stroke={2.6}/></span><strong>{c.title}</strong><b>{c.count}</b></header>
          {c.cards.map(a => (
            <article key={a.prot} className="board-card">
              <strong>{a.dest}</strong>
              <span className="mono">Aviso {a.prot}</span>
              {a.tag && <em className={a.tagTone ? `tone-${a.tagTone}` : ''}>{a.tag}</em>}
            </article>
          ))}
          {c.count > c.cards.length && <p className="board-more">+ {c.count - c.cards.length} {c.count - c.cards.length > 1 ? 'avisos' : 'aviso'}</p>}
        </section>
      ))}
    </div>
  </div>
);

/* ══════════════ 03 · ROTEIRIZAÇÃO — stops + map ══════════════
   Same six avisos, same map. "Sem rota" = arrival order, crossing lines;
   "Rota otimizada" = numbered stops and one continuous route. The list
   rows slide to their new slot (translateY by index). */
const RoutingMock = ({ planned, onToggle }) => {
  const order = planned ? AVISOS_BY_STOP : ROUTE_AVISOS;
  const toggle = (
    <div className="ui-seg" role="group" aria-label="Visualizar avisos">
      <button type="button" className={!planned ? 'is-on' : ''} aria-pressed={!planned}
              data-track="routing_toggle" data-track-label="sem_rota" onClick={() => onToggle(false)}>Sem rota</button>
      <button type="button" className={planned ? 'is-on' : ''} aria-pressed={planned}
              data-track="routing_toggle" data-track-label="rota_otimizada" onClick={() => onToggle(true)}>Rota otimizada</button>
    </div>
  );
  return (
    <UIFrame title="Rota 03" meta="6 avisos" right={toggle} className="route-ui">
      <div className="rt">
        <div className="rt-list" style={{ '--rows': ROUTE_AVISOS.length }}>
          {ROUTE_AVISOS.map(a => (
            <div key={a.prot} className="rt-row" style={{ '--idx': order.indexOf(a) }}>
              <StopBadge n={planned ? a.stop : null} dim={!planned}/>
              <span className="ui-cell-main"><strong>{a.dest}</strong><em>{a.addr}</em></span>
            </div>
          ))}
        </div>
        <div className="rt-map">
          {/* cropped to the band that holds every stop + the start point */}
          <svg viewBox="0 60 560 360" preserveAspectRatio="xMidYMid slice" role="img"
               aria-label={planned ? 'Mapa com as seis paradas numeradas e uma rota contínua' : 'Mapa com as seis entregas ligadas na ordem em que chegaram, com trajetos cruzados'}>
            <MapBase/>
            <path d={RAW_D} className={`raw-line ${planned ? 'is-out' : ''}`}/>
            <path d={ROUTE_D} pathLength="1" className={`route-line ${planned ? 'is-in' : ''}`}/>
            <MapDepot/>
            {MAP_STOPS.slice(1).map(([x, y], i) => (
              <MapPin key={i} n={i + 1} x={x} y={y} state={planned ? 'route' : 'raw'} delay={planned ? 300 + i * 110 : 0}/>
            ))}
          </svg>
        </div>
      </div>
    </UIFrame>
  );
};

/* ══════════════ 03 · IMPRESSÃO — sheets in route order ══════════════
   The sheets appear one by one, numbered like the stops of the route. */
const PrintMock = ({ run }) => (
  <UIFrame title="Impressão da rota 03" meta="6 avisos" className={`print-ui ${run ? 'is-run' : ''}`}>
    <ol className="sheets" aria-label="Avisos prontos para impressão, na ordem da rota">
      {AVISOS_BY_STOP.map((a, i) => (
        <li key={a.prot} style={{ '--i': i }}>
          <span className="sheet-n">{pad2(a.stop)}</span>
          <strong>{a.dest}</strong>
          <i/><i/>
        </li>
      ))}
    </ol>
    <div className="print-action">
      <span className="print-order"><IRoute sz={15}/> Na ordem da rota</span>
      <span className="ui-btn ui-btn-brand"><IPrinter sz={15}/> Imprimir</span>
    </div>
  </UIFrame>
);

/* ══════════════ MINI-ILUSTRAÇÕES — the three pillars under the hero ══════════════ */
const PillarArtFleet = () => (
  <svg viewBox="0 150 560 240" preserveAspectRatio="xMidYMid slice" aria-hidden="true">
    <MapBase/>
    {FLEET.map(f => (
      <g key={f.id} className={`tone-${f.tone}`}>
        <path d={f.driven} className="fleet-driven"/>
        <g transform={`translate(${f.from[0]} ${f.from[1]})`}>
          <circle r="24" className="fleet-me-halo"/>
          <circle r="17" className="fleet-me-dot"/>
          <text y="5" textAnchor="middle" className="fleet-me-n">{f.id}</text>
        </g>
      </g>
    ))}
  </svg>
);

const PillarArtAvisos = () => (
  <div className="pa-avisos" aria-hidden="true">
    <span className="tone-green"><ICheck sz={14} stroke={3}/> Entregues</span>
    <span className="tone-red"><IClose sz={14} stroke={3}/> Negativa</span>
    <span className="tone-blue"><IRoute sz={14} stroke={2.6}/> Em rota</span>
    <span className="tone-violet"><IDoc sz={14} stroke={2.6}/> Ocorrência</span>
  </div>
);

const PillarArtRoute = () => (
  <div className="pa-route" aria-hidden="true">
    <ol>{[1, 2, 3, 4].map(n => <li key={n}>{n}</li>)}</ol>
    <IArrow sz={18}/>
    <span className="pa-printer"><IPrinter sz={24}/></span>
  </div>
);

/* ══════════════ ENTREGGA DRIVER — the courier's screen ══════════════
   What the app does TODAY, and only that: it captures geolocation
   tracking points in the background and sends them to the panel.
   No stops, deliveries or occurrences here — those are not in the app
   yet. The point counter ticks while the card is on screen. */
const DriverAppMock = () => {
  const [ref, on] = useOnScreen();
  const [points, setPoints] = useState(1240);
  useEffect(() => {
    if (!on || REDUCED_MOTION) return;
    const id = setInterval(() => setPoints(p => p + 1), 3400);
    return () => clearInterval(id);
  }, [on]);
  return (
    <div ref={ref} className="drv-stage" aria-hidden="true">
      <div className="drv-phone">
        <div className="drv-notch"/>
        <div className="drv-screen">
          <div className="drv-top"><span>Entregador 03</span><span className="drv-live"><i/>Rastreando</span></div>
          <div className="drv-card">
            <em>Pontos de rastreio capturados</em>
            <strong key={points} className="drv-count">{points.toLocaleString('pt-BR')}</strong>
            <span className="drv-sub"><IPin sz={12}/> Último envio: agora</span>
          </div>
          <div className="drv-stats">
            <div><em>Distância</em><strong>18,4 km</strong></div>
            <div><em>Duração</em><strong>2h 12min</strong></div>
          </div>
          <div className="drv-btn">Pausar rastreamento</div>
        </div>
      </div>
    </div>
  );
};

/* ══════════════ PROVOCAÇÃO — from "where are they?" to the map ══════════════
   Gray roads and question marks until `lit`; then each route draws itself
   and its question mark becomes a courier, one by one. */
const ProvokeMap = ({ lit }) => (
  <div className={`provoke-map ${lit ? 'is-lit' : ''}`}>
    <svg viewBox={`0 0 ${MAP_W} ${MAP_H}`} preserveAspectRatio="xMidYMid slice" role="img"
         aria-label="Mapa em que os pontos de interrogação dão lugar aos intimadores em rota">
      <MapBase/>
      {FLEET.map((f, i) => (
        <g key={f.id} className={`tone-${f.tone}`} style={{ '--i': i }}>
          <path d={f.d} pathLength="1" className="provoke-route"/>
          <g transform={`translate(${f.from[0]} ${f.from[1]})`}>
            <circle r="17" className="provoke-pin"/>
            <text y="6" textAnchor="middle" className="provoke-pin-q">?</text>
            <path d="M-6 .5 L-1.8 4.7 L6.2 -4" fill="none" stroke="#fff" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" className="provoke-pin-ok"/>
          </g>
        </g>
      ))}
    </svg>
    <span className="provoke-map-tag" aria-hidden="true">{lit ? 'Em tempo real' : 'Onde estão?'}</span>
  </div>
);
