// fichaje.eu — Screen: Fichaje (clock in/out, with pause + meal)

const ScreenFichaje = () => {
  // Estado inicial inferido del backend (status del empleado actual)
  const myStatus = (window.BOOTSTRAP && window.BOOTSTRAP.me && window.BOOTSTRAP.me.status) || 'fuera';
  const statusToUi = { fichado: 'working', pausa: 'paused', fuera: 'out', vacaciones: 'out' };
  const [state, setStateRaw] = React.useState(statusToUi[myStatus] || 'out');
  const [busy, setBusy] = React.useState(false);
  const [now, setNow] = React.useState(new Date());
  React.useEffect(() => {
    const id = setInterval(() => setNow(new Date()), 1000);
    return () => clearInterval(id);
  }, []);

  // setState con persistencia en backend
  async function setState(newState) {
    if (busy) return;
    setBusy(true);
    try {
      let fn = null;
      if (newState === 'working' && state === 'out') fn = window.api.punchIn;
      else if (newState === 'working' && (state === 'paused' || state === 'mealing')) fn = window.api.pauseEnd;
      else if (newState === 'paused')  fn = () => window.api.pauseStart('Pausa');
      else if (newState === 'mealing') fn = () => window.api.pauseStart('Comida');
      else if (newState === 'out')     fn = window.api.punchOut;
      if (fn) {
        const r = await fn();
        if (r && r.ok) {
          setStateRaw(newState);
          // Re-cargar bootstrap para refrescar lista de punches del día
          window.api.reloadBootstrap();
        }
      } else {
        setStateRaw(newState);
      }
    } catch (e) {
      console.error('[fichaje] error:', e);
      alert('No se pudo guardar el fichaje. Revisa tu conexión.');
    } finally {
      setBusy(false);
    }
  }

  const timeStr = now.toLocaleTimeString('es-ES', { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false });

  const statusConfig = {
    working: { label: 'Fichando',  dot: 'var(--success-500)', bg: 'var(--success-50)', fg: 'var(--success-600)', counter: '04:43:12' },
    paused:  { label: 'En pausa',  dot: 'var(--warning-500)', bg: 'var(--warning-50)', fg: 'var(--warning-600)', counter: '00:03:18' },
    mealing: { label: 'En comida', dot: 'var(--violet-500)', bg: 'var(--violet-100)', fg: '#6D28D9',           counter: '00:24:05' },
    out:     { label: 'Fuera',     dot: 'var(--slate-400)',  bg: 'var(--slate-100)',  fg: 'var(--slate-700)',  counter: '00:00:00' },
  }[state];

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 18 }}>
      {/* Main clock */}
      <Card style={{ padding: 0, overflow: 'hidden' }}>
        <div style={{
          padding: '28px 32px',
          background: 'linear-gradient(180deg, var(--slate-50) 0%, var(--white) 100%)',
          borderBottom: '1px solid var(--slate-150)',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <div>
              <div style={{ fontSize: 13, color: 'var(--slate-500)', fontWeight: 600 }}>Miércoles, 13 de mayo</div>
              <div className="mono tnum" style={{ fontSize: 56, fontWeight: 700, letterSpacing: '-0.04em', color: 'var(--ink)', marginTop: 4, lineHeight: 1 }}>
                {timeStr.slice(0, 5)}<span style={{ fontSize: 28, color: 'var(--slate-400)' }}>:{timeStr.slice(6)}</span>
              </div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <Badge tone={state === 'working' ? 'success' : state === 'paused' ? 'warning' : state === 'mealing' ? 'violet' : 'slate'} dot>
                {statusConfig.label}
              </Badge>
              <div className="mono tnum" style={{ fontSize: 22, fontWeight: 700, marginTop: 8, color: 'var(--ink)' }}>
                {statusConfig.counter}
              </div>
              <div style={{ fontSize: 12, color: 'var(--slate-500)', marginTop: 2 }}>
                {state === 'working' ? 'Tiempo trabajado hoy' : 'En este estado'}
              </div>
            </div>
          </div>
        </div>

        <div style={{ padding: 28 }}>
          {/* Action buttons */}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 10 }}>
            <button onClick={() => setState('working')} disabled={state === 'working'} style={{
              padding: '14px 12px',
              background: state === 'working' ? 'var(--success-500)' : 'var(--white)',
              color: state === 'working' ? '#fff' : 'var(--slate-700)',
              border: `1px solid ${state === 'working' ? 'var(--success-500)' : 'var(--slate-200)'}`,
              borderRadius: 'var(--r-md)',
              fontSize: 14, fontWeight: 600,
              display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
              opacity: state === 'working' ? 1 : 1,
              cursor: 'pointer',
              boxShadow: state === 'working' ? '0 0 0 4px var(--success-100)' : 'none',
            }}>
              <IPlay size={20}/>
              <span>{state === 'out' ? 'Fichar entrada' : 'Trabajando'}</span>
            </button>
            <button onClick={() => setState('paused')} disabled={state === 'paused'} style={{
              padding: '14px 12px',
              background: state === 'paused' ? 'var(--warning-500)' : 'var(--white)',
              color: state === 'paused' ? '#fff' : 'var(--slate-700)',
              border: `1px solid ${state === 'paused' ? 'var(--warning-500)' : 'var(--slate-200)'}`,
              borderRadius: 'var(--r-md)',
              fontSize: 14, fontWeight: 600,
              display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
              boxShadow: state === 'paused' ? '0 0 0 4px var(--warning-100)' : 'none',
            }}>
              <ICoffee size={20}/>
              <span>Pausa</span>
            </button>
            <button onClick={() => setState('mealing')} disabled={state === 'mealing'} style={{
              padding: '14px 12px',
              background: state === 'mealing' ? 'var(--violet-500)' : 'var(--white)',
              color: state === 'mealing' ? '#fff' : 'var(--slate-700)',
              border: `1px solid ${state === 'mealing' ? 'var(--violet-500)' : 'var(--slate-200)'}`,
              borderRadius: 'var(--r-md)',
              fontSize: 14, fontWeight: 600,
              display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
              boxShadow: state === 'mealing' ? '0 0 0 4px var(--violet-100)' : 'none',
            }}>
              <IUtensils size={20}/>
              <span>Comida</span>
            </button>
            <button onClick={() => setState('out')} disabled={state === 'out'} style={{
              padding: '14px 12px',
              background: state === 'out' ? 'var(--ink)' : 'var(--white)',
              color: state === 'out' ? '#fff' : 'var(--slate-700)',
              border: `1px solid ${state === 'out' ? 'var(--ink)' : 'var(--slate-200)'}`,
              borderRadius: 'var(--r-md)',
              fontSize: 14, fontWeight: 600,
              display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
            }}>
              <IStop size={20}/>
              <span>Fichar salida</span>
            </button>
          </div>

          {/* Timeline */}
          <div style={{ marginTop: 28 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
              <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--ink)' }}>Tu día</div>
              <div style={{ display: 'flex', gap: 12, fontSize: 11, color: 'var(--slate-500)' }}>
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}><span style={{ width: 8, height: 8, borderRadius: 2, background: 'var(--brand-500)' }}/> Trabajo</span>
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}><span style={{ width: 8, height: 8, borderRadius: 2, background: 'var(--warning-500)' }}/> Pausa</span>
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}><span style={{ width: 8, height: 8, borderRadius: 2, background: 'var(--violet-500)' }}/> Comida</span>
              </div>
            </div>
            <div style={{ position: 'relative', height: 38, background: 'var(--slate-100)', borderRadius: 'var(--r-md)', overflow: 'hidden' }}>
              {/* Segments — based on 9 hour window 09:00–18:00 */}
              <div style={{ position: 'absolute', left: '0%', width: '24.4%', height: '100%', background: 'var(--brand-500)' }}/>
              <div style={{ position: 'absolute', left: '24.4%', width: '2.2%', height: '100%', background: 'var(--warning-500)' }}/>
              <div style={{ position: 'absolute', left: '26.6%', width: '28.4%', height: '100%', background: 'var(--brand-500)' }}/>
              <div style={{ position: 'absolute', left: '55%', width: '8.4%', height: '100%', background: 'var(--violet-500)' }}/>
              <div style={{ position: 'absolute', left: '63.4%', width: '0.8%', height: '100%', background: 'var(--brand-500)' }}/>
              {/* Current time marker */}
              <div style={{ position: 'absolute', left: '52%', top: -4, bottom: -4, width: 2, background: 'var(--ink)' }}>
                <div style={{ position: 'absolute', top: -4, left: -4, width: 10, height: 10, borderRadius: 999, background: 'var(--ink)' }}/>
              </div>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 6, fontSize: 11, color: 'var(--slate-500)', fontFamily: 'var(--font-mono)' }}>
              <span>09:00</span><span>11:00</span><span>13:00</span><span>15:00</span><span>17:00</span><span>18:00</span>
            </div>

            {/* Punch list */}
            <div style={{ marginTop: 18, display: 'flex', flexDirection: 'column', gap: 0 }}>
              {TODAY_PUNCHES.map((p, i) => (
                <div key={i} style={{
                  display: 'flex', alignItems: 'center', gap: 14,
                  padding: '11px 0',
                  borderBottom: i < TODAY_PUNCHES.length - 1 ? '1px solid var(--slate-100)' : 'none',
                }}>
                  <div style={{
                    width: 28, height: 28, borderRadius: 999,
                    background: p.type === 'in' ? 'var(--success-50)' : 'var(--warning-50)',
                    color: p.type === 'in' ? 'var(--success-600)' : 'var(--warning-600)',
                    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                  }}>
                    {p.type === 'in' ? <IPlay size={12}/> : <IPause size={12}/>}
                  </div>
                  <div className="mono tnum" style={{ fontSize: 14, fontWeight: 600, color: 'var(--ink)', minWidth: 50 }}>{p.time}</div>
                  <div style={{ flex: 1, fontSize: 14, color: 'var(--slate-700)' }}>{p.label}</div>
                  {p.duration && <Badge tone="warning">{p.duration} min</Badge>}
                  <button style={{ color: 'var(--slate-400)', padding: 4 }}><IMoreH size={16}/></button>
                </div>
              ))}
            </div>
          </div>
        </div>
      </Card>

      {/* Right column */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
        <Card>
          <SectionHead title="Resumen semanal" subtitle="Semana 20 · 11–17 may"/>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <div style={{ padding: 14, background: 'var(--slate-50)', borderRadius: 'var(--r-md)' }}>
              <div style={{ fontSize: 11, color: 'var(--slate-500)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '.06em' }}>Trabajado</div>
              <div className="mono tnum" style={{ fontSize: 20, fontWeight: 700, marginTop: 4 }}>20h 38m</div>
              <div style={{ fontSize: 11, color: 'var(--slate-500)', marginTop: 2 }}>de 24h</div>
            </div>
            <div style={{ padding: 14, background: 'var(--brand-50)', borderRadius: 'var(--r-md)' }}>
              <div style={{ fontSize: 11, color: 'var(--brand-600)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '.06em' }}>Saldo</div>
              <div className="mono tnum" style={{ fontSize: 20, fontWeight: 700, marginTop: 4, color: 'var(--success-600)' }}>+1h 14m</div>
              <div style={{ fontSize: 11, color: 'var(--slate-500)', marginTop: 2 }}>superávit acumulado</div>
            </div>
          </div>

          <div style={{ marginTop: 14, display: 'flex', flexDirection: 'column', gap: 8 }}>
            {[
              { d: 'Lunes 11',     w: '8h 03m', e: '08:58 → 17:35', sup: '+3m'  },
              { d: 'Martes 12',    w: '7h 50m', e: '09:12 → 17:30', sup: '-10m' },
              { d: 'Miércoles 13', w: '4h 43m', e: '09:02 → (en curso)', sup: '—', live: true },
            ].map((d, i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '8px 0', borderTop: i ? '1px solid var(--slate-100)' : 'none' }}>
                <div style={{ width: 86, fontSize: 13, fontWeight: 600, color: d.live ? 'var(--brand-600)' : 'var(--ink)' }}>{d.d}</div>
                <div className="mono tnum" style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)' }}>{d.w}</div>
                <div className="mono" style={{ flex: 1, fontSize: 12, color: 'var(--slate-500)' }}>{d.e}</div>
                {d.live ? <Badge tone="brand" dot>en curso</Badge> : <span style={{ fontSize: 12, fontWeight: 600, color: d.sup.startsWith('+') ? 'var(--success-600)' : 'var(--slate-500)' }}>{d.sup}</span>}
              </div>
            ))}
          </div>
        </Card>

        <Card>
          <SectionHead title="Ubicación de fichaje" subtitle="Validado por geolocalización"/>
          <div style={{ position: 'relative', height: 120, borderRadius: 'var(--r-md)', overflow: 'hidden', background: 'var(--slate-100)' }}>
            {/* Decorative map */}
            <svg width="100%" height="100%" viewBox="0 0 400 120" preserveAspectRatio="xMidYMid slice" style={{ display: 'block' }}>
              <rect width="400" height="120" fill="#EAEEF3"/>
              {/* Streets */}
              <path d="M0 60 L400 50" stroke="#fff" strokeWidth="4"/>
              <path d="M0 85 L400 90" stroke="#fff" strokeWidth="3"/>
              <path d="M120 0 L130 120" stroke="#fff" strokeWidth="4"/>
              <path d="M260 0 L255 120" stroke="#fff" strokeWidth="3"/>
              <path d="M340 0 L345 120" stroke="#fff" strokeWidth="2"/>
              {/* Park */}
              <rect x="0" y="0" width="120" height="60" fill="#D1FAE5" opacity="0.6"/>
              <rect x="260" y="50" width="80" height="40" fill="#DBEAFE" opacity="0.5"/>
              {/* Marker */}
              <circle cx="200" cy="65" r="22" fill="#1E40AF" opacity="0.15"/>
              <circle cx="200" cy="65" r="10" fill="#1E40AF"/>
              <circle cx="200" cy="65" r="4" fill="#fff"/>
            </svg>
          </div>
          <div style={{ marginTop: 12, display: 'flex', alignItems: 'flex-start', gap: 10 }}>
            <IMapPin size={16} style={{ color: 'var(--brand-600)', marginTop: 2 }}/>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)' }}>Oficina Valencia · C/ Colón 22</div>
              <div style={{ fontSize: 12, color: 'var(--slate-500)' }}>Dispositivo: MacBook Pro · IP autorizada</div>
            </div>
            <Badge tone="success" dot>Verificado</Badge>
          </div>
        </Card>
      </div>
    </div>
  );
};

Object.assign(window, { ScreenFichaje });
