// Guide: lightweight onboarding + persistent help panel
// First-run shows a 4-step welcome. After dismissal, a "Guía" button stays
// in the topbar and re-opens the same panel with a checklist + module tips.

const GUIDE_STEPS = [
  {
    title: 'Bienvenida a Blueways',
    body: 'Centraliza todas las solicitudes de inquilinos: incidencias, mantenimiento y seguimientos. Te enseñamos el sistema en 4 pasos.',
  },
  {
    title: '1. Configura tu agente',
    body: 'En "Agentes IA" definirás la personalidad, el protocolo de triaje y los scripts. Empieza con la plantilla "Recepción WhatsApp".',
    cta: { label: 'Ir a Agentes IA', page: 'agents' },
  },
  {
    title: '2. Revisa tickets entrantes',
    body: 'En "Tickets" verás cada solicitud por estado: abierta, programada, en curso, resuelta. Filtra por categoría y prioridad.',
    cta: { label: 'Ir a Tickets', page: 'tickets' },
  },
  {
    title: '3. Supervisa conversaciones',
    body: 'En "Conversaciones" verás cada llamada y chat con inquilinos en tiempo real. Puedes intervenir y tomar el control humano cuando quieras.',
    cta: { label: 'Ir a Conversaciones', page: 'conversations' },
  },
];

const CHECKLIST = [
  { id: 'agent',    label: 'Crear primer agente IA',          page: 'agents'      },
  { id: 'tech',     label: 'Añadir técnicos a la red',         page: 'technicians' },
  { id: 'ticket',   label: 'Resolver el primer ticket',       page: 'tickets'     },
  { id: 'team',     label: 'Invitar a tu equipo',             page: 'admin'       },
  { id: 'billing',  label: 'Confirmar plan de facturación',   page: 'billing'     },
];

function Guide({ open, onClose, onNav }) {
  const [firstRun, setFirstRun] = React.useState(() => !localStorage.getItem('bw_guide_seen'));
  const [step, setStep] = React.useState(0);
  const [done, setDone] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem('bw_guide_done') || '{}'); }
    catch { return {}; }
  });

  React.useEffect(() => {
    if (!open) return;
    if (firstRun) setStep(0);
  }, [open, firstRun]);

  const finishFirstRun = () => {
    localStorage.setItem('bw_guide_seen', '1');
    setFirstRun(false);
  };

  const toggleDone = (id) => {
    const next = { ...done, [id]: !done[id] };
    setDone(next);
    localStorage.setItem('bw_guide_done', JSON.stringify(next));
  };

  if (!open) return null;

  const completed = CHECKLIST.filter(c => done[c.id]).length;

  return (
    <>
      <div onClick={onClose} style={{ position:'fixed', inset: 0, background:'rgba(15,23,42,.32)', zIndex: 90, animation: 'fade .2s ease' }} />
      <aside style={{
        position:'fixed', top: 0, right: 0, bottom: 0, width: 420, zIndex: 91,
        background:'white', borderLeft:'1px solid var(--color-border)',
        boxShadow:'-12px 0 40px -12px rgba(15,23,42,.18)',
        display:'flex', flexDirection:'column',
        animation: 'slideIn .25s cubic-bezier(.2,.8,.2,1)'
      }}>
        <div style={{ padding:'18px 24px', borderBottom:'1px solid var(--color-border)', display:'flex', alignItems:'center', gap: 10 }}>
          <div style={{ width: 32, height: 32, borderRadius: 8, background:'var(--color-accent-light)', color:'var(--color-accent)', display:'grid', placeItems:'center' }}>
            <I.Book size={16} />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 15, fontWeight: 600 }}>Guía de Blueways</div>
            <div style={{ fontSize: 12, color:'var(--color-text-secondary)' }}>Aprende y consulta cuando quieras</div>
          </div>
          <button className="icon-btn" onClick={onClose}><I.X size={16} /></button>
        </div>

        {firstRun ? (
          <div style={{ flex: 1, padding: 28, overflow:'auto', display:'flex', flexDirection:'column' }}>
            <div style={{ display:'flex', gap: 6, marginBottom: 24 }}>
              {GUIDE_STEPS.map((_, i) => (
                <div key={i} style={{ flex: 1, height: 3, borderRadius: 2, background: i <= step ? 'var(--color-accent)' : 'var(--color-border)' }} />
              ))}
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily:'var(--font-ui)', fontWeight: 400, fontSize: 26, letterSpacing:'-0.02em', marginBottom: 12, color:'var(--brand-navy)' }}>
                {GUIDE_STEPS[step].title}
              </div>
              <div style={{ fontSize: 14, lineHeight: 1.6, color:'var(--color-text-secondary)' }}>
                {GUIDE_STEPS[step].body}
              </div>
              {GUIDE_STEPS[step].cta && (
                <button
                  className="btn btn-secondary btn-sm"
                  style={{ marginTop: 20 }}
                  onClick={() => { onNav(GUIDE_STEPS[step].cta.page); onClose(); }}
                >
                  {GUIDE_STEPS[step].cta.label} <I.ArrowR size={14} />
                </button>
              )}
            </div>
            <div style={{ display:'flex', gap: 8, justifyContent:'space-between', marginTop: 24 }}>
              <button className="btn btn-ghost btn-sm" onClick={finishFirstRun}>Saltar</button>
              <div style={{ display:'flex', gap: 8 }}>
                {step > 0 && <button className="btn btn-secondary btn-sm" onClick={() => setStep(step - 1)}>Atrás</button>}
                {step < GUIDE_STEPS.length - 1
                  ? <button className="btn btn-primary btn-sm" onClick={() => setStep(step + 1)}>Siguiente</button>
                  : <button className="btn btn-primary btn-sm" onClick={finishFirstRun}>Empezar a usar Blueways</button>
                }
              </div>
            </div>
          </div>
        ) : (
          <div style={{ flex: 1, overflow:'auto' }}>
            {/* Checklist */}
            <div style={{ padding: 24, borderBottom:'1px solid var(--color-border)' }}>
              <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline', marginBottom: 14 }}>
                <div style={{ fontSize: 13, fontWeight: 600, color:'var(--color-text-primary)' }}>Primeros pasos</div>
                <div style={{ fontSize: 12, color:'var(--color-text-secondary)' }}>{completed}/{CHECKLIST.length} completados</div>
              </div>
              <div style={{ display:'flex', flexDirection:'column', gap: 4 }}>
                {CHECKLIST.map(item => (
                  <div key={item.id} style={{ display:'flex', alignItems:'center', gap: 10, padding:'10px 4px', borderRadius: 6 }}>
                    <button
                      onClick={() => toggleDone(item.id)}
                      style={{
                        width: 18, height: 18, borderRadius: '50%',
                        border: '1.5px solid ' + (done[item.id] ? 'var(--color-success)' : 'var(--color-border)'),
                        background: done[item.id] ? 'var(--color-success)' : 'white',
                        color: 'white', display:'grid', placeItems:'center', flex:'0 0 18px'
                      }}
                    >
                      {done[item.id] && <I.Check size={11} />}
                    </button>
                    <div style={{ flex: 1, fontSize: 13.5, color: done[item.id] ? 'var(--color-text-muted)' : 'var(--color-text-primary)', textDecoration: done[item.id] ? 'line-through' : 'none' }}>
                      {item.label}
                    </div>
                    <button className="btn btn-ghost btn-sm" style={{ padding:'2px 8px' }} onClick={() => { onNav(item.page); onClose(); }}>
                      Abrir <I.ArrowR size={12} />
                    </button>
                  </div>
                ))}
              </div>
            </div>

            {/* Help topics */}
            <div style={{ padding: 24 }}>
              <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 12 }}>Ayuda por módulo</div>
              <div style={{ display:'flex', flexDirection:'column', gap: 2 }}>
                {[
                  { t:'Cómo crear un agente IA', p:'agents', i:'Bot' },
                  { t:'Cómo gestionar técnicos y dispatches', p:'technicians', i:'Wrench' },
                  { t:'Cómo intervenir en una llamada', p:'conversations', i:'Chat' },
                  { t:'Cómo leer el reporting de un agente', p:'reporting', i:'Chart' },
                  { t:'Cómo gestionar facturación variable', p:'billing', i:'Card' },
                ].map(h => {
                  const Ic = I[h.i];
                  return (
                    <button key={h.t} onClick={() => { onNav(h.p); onClose(); }}
                      style={{ display:'flex', alignItems:'center', gap: 10, padding:'10px 8px', border:0, background:'transparent', textAlign:'left', borderRadius: 6, cursor:'pointer', fontSize: 13.5, color:'var(--color-text-primary)' }}
                      onMouseEnter={e => e.currentTarget.style.background='var(--color-surface)'}
                      onMouseLeave={e => e.currentTarget.style.background='transparent'}>
                      <Ic size={14} />
                      <span style={{ flex: 1 }}>{h.t}</span>
                      <I.ArrowR size={12} />
                    </button>
                  );
                })}
              </div>
            </div>

            <div style={{ padding:'0 24px 24px' }}>
              <div style={{ padding: 16, background:'var(--color-surface)', borderRadius: 10, border:'1px solid var(--color-border)' }}>
                <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 4 }}>¿Necesitas ayuda directa?</div>
                <div style={{ fontSize: 12.5, color:'var(--color-text-secondary)', lineHeight: 1.5, marginBottom: 12 }}>Tu equipo de éxito te responde en menos de 2 horas.</div>
                <button className="btn btn-secondary btn-sm" style={{ width:'100%', justifyContent:'center' }}>
                  Contactar con soporte
                </button>
              </div>
            </div>

            <div style={{ padding:'12px 24px', borderTop:'1px solid var(--color-border)', display:'flex', justifyContent:'space-between', alignItems:'center' }}>
              <button className="btn btn-ghost btn-sm" onClick={() => { localStorage.removeItem('bw_guide_seen'); setFirstRun(true); setStep(0); }}>
                <I.RefreshCw size={12} /> Repetir tour
              </button>
              <span style={{ fontSize: 11, color:'var(--color-text-muted)' }}>v1.0 · 2026</span>
            </div>
          </div>
        )}
      </aside>
      <style>{`
        @keyframes fade { from { opacity: 0 } to { opacity: 1 } }
        @keyframes slideIn { from { transform: translateX(20px); opacity: .6 } to { transform: translateX(0); opacity: 1 } }
      `}</style>
    </>
  );
}

window.Guide = Guide;
