// UI.jsx — shared components: Logo, LineChip, StatusBar, BottomNav, AppBar, SchematicMap, Skeleton

function Logo({ size = 30, variant = 'default' }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
      <img src="assets/logo.png" alt="alSubte" style={{ height: size, width: size, borderRadius: 8, objectFit: 'cover' }} />
      <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: size * 0.58, letterSpacing: '-.02em', color: 'rgb(255, 239, 0)' }}>
        al<span style={{ fontWeight: 800, color: '#F7910A' }}>Subte</span>
      </div>
    </div>
  );
}

function LineChip({ id, size = 'md', onClick, style = {} }) {
  const cls = ['line-chip', 'solid-' + id.toLowerCase(), size, id === 'H' ? 'h' : ''].filter(Boolean).join(' ');
  return (
    <div className={cls} onClick={onClick} style={{ cursor: onClick ? 'pointer' : 'default', ...style }}>
      {id === 'P' ? 'P' : id}
    </div>
  );
}

function StatusBar() {
  return (
    <div className="status-bar">
      <span>9:41</span>
      <div className="indicators">
        <I name="signal" size={16} />
        <I name="wifi" size={16} />
        <I name="battery" size={20} />
      </div>
    </div>
  );
}

function BottomNav({ active, onChange, t }) {
  const items = [
    { id: 'main',           label: t('home'),     icon: 'home'    },
    { id: 'map',            label: t('map'),      icon: 'map'     },
    { id: 'incidentReport', label: t('report'),   icon: 'warning' },
    { id: 'news',           label: t('news'),     icon: 'news'    },
    { id: 'settings',       label: t('settings'), icon: 'settings'},
  ];
  return (
    <nav className="bottom-nav">
      {items.map(it => (
        <button key={it.id} className={'nav-item' + (active === it.id ? ' active' : '')} onClick={() => onChange(it.id)}>
          <I name={it.icon} size={22} />
          <span>{it.label}</span>
          <div className="dot-indicator" />
        </button>
      ))}
    </nav>
  );
}

function AppBar({ title, subtitle, left, right, large = false }) {
  return (
    <header className="app-bar" style={{ paddingTop: large ? 8 : 14, paddingBottom: large ? 4 : 10 }}>
      {left}
      <div style={{ flex: 1, minWidth: 0 }}>
        {/* font-size reset so callers can pass arbitrary JSX without inheriting h1 size */}
        <h1 style={{ fontSize: large ? 28 : 22, lineHeight: 1.1 }}>{title}</h1>
        {subtitle && <div className="subtitle" style={{ marginTop: 3 }}>{subtitle}</div>}
      </div>
      {right}
    </header>
  );
}

function Skeleton({ w = '100%', h = 16, r = 6 }) {
  return <div style={{ width: w, height: h, background: 'var(--ink-200)', borderRadius: r, opacity: .6 }} />;
}

// Schematic map — draws SCHEMATIC.lines as SVG, animates trains along the paths
function SchematicMap({ tick = 0, selectedLines = ['A','B','C','D','E','H','P'], onSelect, highlightedLine = null, showTrains = true, showUserLocation = false, userPos = [490, 440] }) {
  const lines = Object.entries(SCHEMATIC.lines).filter(([id]) => selectedLines.includes(id));
  return (
    <svg viewBox={SCHEMATIC.viewBox} preserveAspectRatio="xMidYMid meet" style={{ width: '100%', height: '100%' }}>
      {/* Río de la Plata hint */}
      <path d="M0,0 L1000,0 L1000,120 Q800,100 600,130 Q400,150 200,140 Q100,138 0,170 Z" fill="var(--surface-2)" />
      {/* Schematic lines */}
      {lines.map(([id, data]) => {
        const dim = highlightedLine && highlightedLine !== id ? 0.25 : 1;
        const d = data.path.map((p, i) => (i === 0 ? 'M' : 'L') + p[0] + ' ' + p[1]).join(' ');
        return (
          <g key={id} style={{ opacity: dim, cursor: onSelect ? 'pointer' : 'default' }} onClick={() => onSelect && onSelect(id)}>
            <path d={d} stroke={data.color} strokeWidth="10" fill="none" strokeLinecap="round" strokeLinejoin="round" />
            {data.path.map((p, i) => (
              <circle key={i} cx={p[0]} cy={p[1]} r="5" fill="white" stroke={data.color} strokeWidth="2.5" />
            ))}
            {/* Animated train */}
            {showTrains && <SchematicTrain path={data.path} color={data.color} tick={tick} seed={id.charCodeAt(0)} />}
          </g>
        );
      })}
      {/* Line labels at ends */}
      {lines.map(([id, data]) => {
        const start = data.path[0], end = data.path[data.path.length - 1];
        return (
          <g key={id + '-lbl'} style={{ pointerEvents: 'none' }}>
            <circle cx={end[0]} cy={end[1]} r="14" fill={data.color} />
            <text x={end[0]} y={end[1] + 5} textAnchor="middle" fill={id === 'H' ? '#0B1220' : 'white'} fontSize="16" fontWeight="800" fontFamily="Nunito">{id}</text>
          </g>
        );
      })}
      {/* User location */}
      {showUserLocation && (
        <g>
          <circle cx={userPos[0]} cy={userPos[1]} r="30" fill="#0078B1" opacity=".15">
            <animate attributeName="r" from="14" to="34" dur="1.8s" repeatCount="indefinite" />
            <animate attributeName="opacity" from=".35" to="0" dur="1.8s" repeatCount="indefinite" />
          </circle>
          <circle cx={userPos[0]} cy={userPos[1]} r="10" fill="#0078B1" stroke="white" strokeWidth="3" />
        </g>
      )}
    </svg>
  );
}

function SchematicTrain({ path, color, tick, seed }) {
  // Simulate trains moving along the polyline in both directions
  const segments = [];
  for (let i = 0; i < path.length - 1; i++) {
    const [x1, y1] = path[i], [x2, y2] = path[i + 1];
    const len = Math.hypot(x2 - x1, y2 - y1);
    segments.push({ x1, y1, x2, y2, len });
  }
  const totalLen = segments.reduce((a, s) => a + s.len, 0);
  const speed = 60; // units per tick
  const offset1 = ((tick * speed + seed * 37) % totalLen);
  const offset2 = (totalLen - ((tick * speed + seed * 29) % totalLen));
  const getPos = (d) => {
    let remain = d;
    for (const s of segments) {
      if (remain <= s.len) {
        const f = remain / s.len;
        return [s.x1 + (s.x2 - s.x1) * f, s.y1 + (s.y2 - s.y1) * f];
      }
      remain -= s.len;
    }
    return [path[path.length - 1][0], path[path.length - 1][1]];
  };
  const p1 = getPos(offset1);
  const p2 = getPos(offset2);
  return (
    <g>
      <rect x={p1[0] - 9} y={p1[1] - 9} width="18" height="18" rx="5" fill={color} stroke="white" strokeWidth="2.5" />
      <rect x={p2[0] - 9} y={p2[1] - 9} width="18" height="18" rx="5" fill={color} stroke="white" strokeWidth="2.5" opacity=".75" />
    </g>
  );
}

// Geographic map: uses the uploaded real SVG via <object> or tile placeholder
function GeographicMap({ selectedLines = ['A','B','C','D','E','H','P'], userPos = { x: 52, y: 48 } }) {
  return (
    <div style={{ position: 'relative', width: '100%', height: '100%', overflow: 'hidden', background: '#E7EEF2' }}>
      {/* Fake map tile background */}
      <svg viewBox="0 0 400 400" preserveAspectRatio="xMidYMid slice" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }}>
        <defs>
          <pattern id="grid" width="24" height="24" patternUnits="userSpaceOnUse">
            <path d="M24 0H0v24" fill="none" stroke="#D4DFE6" strokeWidth="1" />
          </pattern>
        </defs>
        <rect width="100%" height="100%" fill="#EAF0F3" />
        <rect width="100%" height="100%" fill="url(#grid)" />
        {/* Rio de la Plata */}
        <path d="M280,0 L400,0 L400,180 Q340,140 300,100 Q280,60 280,0 Z" fill="#B8D3DD" />
        {/* Avenidas */}
        <path d="M0,200 L400,180" stroke="#C6D0D8" strokeWidth="6" />
        <path d="M200,0 L220,400" stroke="#C6D0D8" strokeWidth="6" />
        <path d="M0,280 L400,260" stroke="#C6D0D8" strokeWidth="4" />
        <path d="M120,0 L140,400" stroke="#C6D0D8" strokeWidth="4" />
        <path d="M280,0 L300,400" stroke="#C6D0D8" strokeWidth="4" />
        {/* Subway lines (real-ish curved paths) */}
        {selectedLines.includes('A') && <path d="M40,230 Q100,225 180,220 T300,210" stroke="#0078B1" strokeWidth="5" fill="none" strokeLinecap="round" />}
        {selectedLines.includes('B') && <path d="M290,230 Q270,200 240,160 Q210,120 170,90 Q130,65 80,50" stroke="#E13A40" strokeWidth="5" fill="none" strokeLinecap="round" />}
        {selectedLines.includes('C') && <path d="M240,100 Q245,160 250,220 Q255,260 260,300" stroke="#2285BB" strokeWidth="5" fill="none" strokeLinecap="round" />}
        {selectedLines.includes('D') && <path d="M310,220 Q260,180 210,150 Q160,125 110,100 Q80,85 50,70" stroke="#008B6E" strokeWidth="5" fill="none" strokeLinecap="round" />}
        {selectedLines.includes('E') && <path d="M260,100 Q290,200 280,250 Q250,290 190,320 Q130,340 70,360" stroke="#87307E" strokeWidth="5" fill="none" strokeLinecap="round" />}
        {selectedLines.includes('H') && <path d="M330,60 Q320,150 310,230 Q305,300 305,360" stroke="#F5B301" strokeWidth="5" fill="none" strokeLinecap="round" />}
        {selectedLines.includes('P') && <path d="M70,360 Q120,370 180,378" stroke="#7B61FF" strokeWidth="4" fill="none" strokeLinecap="round" strokeDasharray="2,3" />}
      </svg>
      {/* User location */}
      <div style={{ position: 'absolute', left: userPos.x + '%', top: userPos.y + '%', transform: 'translate(-50%,-50%)' }}>
        <div style={{ width: 40, height: 40, borderRadius: '50%', background: 'rgba(0,120,177,.2)', position: 'absolute', inset: -10, animation: 'pulse 1.8s ease-in-out infinite' }} />
        <div style={{ width: 18, height: 18, borderRadius: '50%', background: '#0078B1', border: '3px solid white', boxShadow: '0 2px 6px rgba(0,0,0,.3)', position: 'relative' }} />
      </div>
    </div>
  );
}

Object.assign(window, { Logo, LineChip, StatusBar, BottomNav, AppBar, Skeleton, SchematicMap, GeographicMap });
