/* GestiFalla — Pantallas A: Login, Home, Ficha Fallero */

/* ============================================================
   LOGIN
   ============================================================ */
function LoginScreen({ onLogin }) {
  const [show, setShow] = useState(false);
  const [user, setUser] = useState('04821');
  const [pass, setPass] = useState('brustengos');
  return (
    <div className="gf-screen" style={{ background: 'var(--gf-bg)' }}>
      <div className="gf-body" style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', padding: '0 24px' }}>
        {/* Decorative top stripe block */}
        <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 190, background: 'var(--gf-primary)' }}>
          <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, height: 3, background: 'var(--gf-accent)' }} />
        </div>

        <div style={{ position: 'relative', zIndex: 2, marginTop: -20 }}>
          <div style={{ textAlign: 'center', marginBottom: 26 }}>
            <div style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 60, height: 60, borderRadius: 16, background: '#fff', boxShadow: 'var(--gf-shadow-pop)', marginBottom: 16 }}>
              <span style={{ fontSize: 30, fontWeight: 800, color: 'var(--gf-primary)' }}>G<span style={{ color: 'var(--gf-accent)' }}>F</span></span>
            </div>
            <div className="gf-logo" style={{ fontSize: 26, color: 'var(--gf-primary)' }}>Gesti<b>Falla</b></div>
          </div>

          <div className="gf-card" style={{ padding: 22, boxShadow: 'var(--gf-shadow-pop)', border: 'none' }}>
            <div style={{ fontSize: 17, fontWeight: 800, marginBottom: 2 }}>Acceso fallero</div>
            <div className="gf-sub" style={{ marginBottom: 20 }}>{DATA.falla.nombre}</div>

            <div className="gf-field">
              <label className="gf-label">Usuario · N.º censo</label>
              <div className="gf-input-wrap">
                <input className="gf-input" value={user} onChange={e => setUser(e.target.value)} placeholder="N.º de censo" />
              </div>
            </div>
            <div className="gf-field">
              <label className="gf-label">Contraseña</label>
              <div className="gf-input-wrap">
                <input className="gf-input gf-input--icon" type={show ? 'text' : 'password'} value={pass} onChange={e => setPass(e.target.value)} placeholder="Contraseña" />
                <button className="gf-eye" onClick={() => setShow(s => !s)}>{show ? <I.eyeOff /> : <I.eye />}</button>
              </div>
            </div>

            <div style={{ textAlign: 'right', marginBottom: 18 }}>
              <span style={{ fontSize: 12, fontWeight: 700, color: 'var(--gf-primary)' }}>¿Olvidaste la contraseña?</span>
            </div>

            <button className="gf-btn gf-btn--primary" onClick={onLogin}>Acceder</button>
          </div>

          <div style={{ textAlign: 'center', marginTop: 22, fontSize: 11, color: 'var(--gf-muted)', fontWeight: 600 }}>
            Ejercicio {DATA.falla.ejercicio} · Sección {DATA.falla.seccion}
          </div>
        </div>
      </div>
    </div>
  );
}

/* ============================================================
   HOME
   ============================================================ */
function HomeScreen({ onNav, toast }) {
  const f = DATA.fallero;
  const feedColor = { ok: 'var(--gf-green)', info: 'var(--gf-primary)', alert: 'var(--gf-red)' };
  const quick = [
    { id: 'ficha', t: 'Mi ficha', s: 'Datos falleros', ico: I.id },
    { id: 'eventos', t: 'Eventos', s: '5 próximos', ico: I.calendar },
    { id: 'familia', t: 'Unidad familiar', s: `${f.miembros} miembros`, ico: I.users },
    { id: 'cuotas', t: 'Cuotas', s: 'Al corriente', ico: I.euro },
  ];
  return (
    <div className="gf-screen">
      <Header>
        <HeaderBrand onBell={() => toast('Sin notificaciones nuevas')} onChat={() => toast('Mensajería')} />
        <div className="gf-header__greet">Bon dia,</div>
        <div className="gf-header__name">{f.corto} 👋</div>
      </Header>

      <div className="gf-body gf-body--padnav">
        <div style={{ padding: '14px 16px 0' }}>
          {/* Monedero card */}
          <button className="gf-card gf-fadein" style={{ width: '100%', textAlign: 'left', padding: 0, overflow: 'hidden', border: 'none', display: 'block' }} onClick={() => onNav('monedero')}>
            <div className="gf-hero" style={{ borderRadius: 'var(--gf-r-md) var(--gf-r-md) 0 0', padding: '16px 16px 14px' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 13 }}>
                <div className="gf-coin" style={{ width: 48, height: 48, fontSize: 22 }}>{DATA.falla.moneda.simbolo}</div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 11, fontWeight: 700, color: 'rgba(255,255,255,0.7)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Mi monedero · {DATA.falla.moneda.nombre}</div>
                  <div className="gf-balance" style={{ fontSize: 28, marginTop: 3 }}>{f.saldo} <small>{DATA.falla.moneda.simbolo}</small></div>
                </div>
                <I.chevR style={{ color: 'rgba(255,255,255,0.6)' }} />
              </div>
            </div>
            <div className="gf-strip" style={{ borderRadius: 0, background: '#fff' }}>
              {[{ l: 'Traspasar', i: I.transfer }, { l: 'Recargar', i: I.plus }, { l: 'Historial', i: I.list }].map((a, k) => (
                <div key={k} className="gf-strip__item" style={{ color: 'var(--gf-primary)' }}>
                  <a.i width="20" height="20" />
                  <span className="gf-strip__lbl">{a.l}</span>
                </div>
              ))}
            </div>
          </button>

          {/* Quick grid 2x2 */}
          <div className="gf-eyebrow" style={{ margin: '20px 0 10px' }}>Accesos rápidos</div>
          <div className="gf-quick">
            {quick.map(q => (
              <button key={q.id} className="gf-quick__item" onClick={() => onNav(q.id === 'familia' || q.id === 'cuotas' ? 'ficha' : q.id)}>
                <div className="gf-quick__ico"><q.ico width="22" height="22" /></div>
                <div>
                  <div className="gf-quick__title">{q.t}</div>
                  <div className="gf-quick__sub">{q.s}</div>
                </div>
              </button>
            ))}
          </div>

          {/* Feed */}
          <div className="gf-eyebrow" style={{ margin: '22px 0 10px', display: 'flex', justifyContent: 'space-between' }}>
            <span>Novedades</span>
            <span style={{ color: 'var(--gf-primary)' }}>Ver todo</span>
          </div>
          <div className="gf-card" style={{ overflow: 'hidden' }}>
            {DATA.novedades.map((n, k) => (
              <div key={k} className="gf-feed__item">
                <span className="gf-feed__dot" style={{ background: feedColor[n.tipo] }} />
                <div className="gf-feed__body">
                  <div className="gf-feed__txt">{n.txt}</div>
                  <div className="gf-feed__time">{n.time}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      <BottomNav active="home" onNav={onNav} />
    </div>
  );
}

/* ============================================================
   FICHA FALLERO — acordeón 7 bloques
   ============================================================ */
function AccItem({ item, open, onToggle, onSave }) {
  const ref = useRef(null);
  const [h, setH] = useState(0);
  useEffect(() => { if (ref.current) setH(open ? ref.current.scrollHeight : 0); }, [open, item]);
  const Icon = item.icon;
  return (
    <div className="gf-acc__item">
      <button className={`gf-acc__head${open ? ' gf-acc__head--open' : ''}`} onClick={onToggle}>
        <div className="gf-acc__ico"><Icon width="20" height="20" /></div>
        <div className="gf-acc__titles">
          <div className="gf-acc__title">{item.title}{item.ro && <span className="gf-ro" style={{ marginLeft: 7, fontSize: 8 }}>SOLO LECTURA</span>}</div>
          <div className="gf-acc__preview">{item.preview}</div>
        </div>
        <I.chevD className={`gf-acc__chev${open ? ' gf-acc__chev--open' : ''}`} />
      </button>
      <div className="gf-acc__panel" style={{ height: h }}>
        <div className="gf-acc__inner" ref={ref}>
          {item.render(onSave)}
        </div>
      </div>
    </div>
  );
}

function FichaScreen({ onNav, onCarnet, toast }) {
  const f = DATA.fallero;
  const [open, setOpen] = useState('datos');
  const [obs, setObs] = useState('Disponible para montaje del casal. Alérgico a frutos secos (cena germanor).');

  const SaveBtn = () => (
    <button className="gf-btn gf-btn--gold" style={{ height: 44, marginTop: 14 }} onClick={() => toast('Cambios guardados correctamente')}>
      <I.check /> Guardar sección
    </button>
  );
  const grid = (pairs) => <div className="gf-cellgrid">{pairs.map((p, i) => <Cell key={i} label={p[0]} value={p[1]} />)}</div>;

  const blocks = [
    { id: 'datos', icon: I.user, title: 'Datos personales', preview: `${f.dni} · ${f.telefono}`, render: (save) => (<>
      {grid([['DNI / NIE', f.dni], ['Nacimiento', f.nacimiento], ['Teléfono', f.telefono], ['Email', f.email]])}
      <SaveBtn />
    </>) },
    { id: 'uf', icon: I.users, title: 'Unidad familiar', preview: `${f.uf} · ${f.miembros} miembros`, render: () => (<>
      {grid([['Nombre UF', f.uf], ['Miembros', String(f.miembros)], ['IBAN', f.iban], ['Titular', f.corto]])}
      <SaveBtn />
    </>) },
    { id: 'dom', icon: I.home2, title: 'Domicilio', preview: `${f.direccion} · ${f.poblacion}`, render: () => (<>
      {grid([['Dirección', f.direccion], ['Cód. postal', f.cp], ['Población', f.poblacion], ['Provincia', 'València']])}
      <SaveBtn />
    </>) },
    { id: 'eco', icon: I.euro, title: 'Datos económicos', ro: true, preview: `${f.formaPago} · ${f.cuotaTotal}`, render: () => (<>
      {grid([['Forma de pago', f.formaPago], ['Cuota total', f.cuotaTotal], ['Estado cuota', 'Al corriente'], ['Próximo cargo', '01/06']])}
    </>) },
    { id: 'fall', icon: I.star, title: 'Datos falleros', ro: true, preview: `${f.cargo} · ${f.anios} años`, render: () => (<>
      {grid([['Cargo', f.cargo], ['Recompensa', f.recompensa], ['Sección', f.seccion], ['Años fallero', String(f.anios)]])}
    </>) },
    { id: 'tienda', icon: I.cart, title: 'Tienda', ro: true, preview: `Cuenta: ${f.cuentaTienda}`, render: () => (<>
      {grid([['Estado cuenta', f.cuentaTienda], ['Pedidos activos', '0'], ['Saldo tienda', '0,00 €'], ['Última compra', '14/05']])}
    </>) },
    { id: 'obs', icon: I.note, title: 'Observaciones', preview: obs.slice(0, 38) + '…', render: () => (<>
      <textarea value={obs} onChange={e => setObs(e.target.value)} style={{ width: '100%', minHeight: 84, border: '1px solid var(--gf-border)', borderRadius: 'var(--gf-r-sm)', padding: 11, fontSize: 13, fontWeight: 600, color: 'var(--gf-text)', fontFamily: 'inherit', resize: 'none', outline: 'none', background: 'var(--gf-bg)' }} />
      <SaveBtn />
    </>) },
  ];

  return (
    <div className="gf-screen">
      <Header>
        <SubHeader title="Mi ficha" right={<button className="gf-iconbtn" onClick={onCarnet}><I.qr /></button>} />
      </Header>

      <div className="gf-body gf-body--padnav">
        {/* Hero ficha */}
        <div style={{ background: 'var(--gf-primary)', padding: '4px 16px 0' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, paddingBottom: 14 }}>
            <Avatar name={f.nombre} size={62} ring={3} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 18, fontWeight: 800, color: '#fff', letterSpacing: '-0.01em' }}>{f.nombre}</div>
              <div style={{ marginTop: 6 }}>
                <span className="gf-badge"><I.star /> {f.cargo}</span>
              </div>
            </div>
          </div>
          {/* Barra de códigos */}
          <div style={{ display: 'flex', background: 'var(--gf-primary-dark)', borderRadius: '10px 10px 0 0', overflow: 'hidden' }}>
            {[['N.º JCF', f.jcf], ['N.º Censo', f.censo], ['Estado', f.estado]].map((c, i) => (
              <div key={i} style={{ flex: 1, padding: '9px 12px', position: 'relative' }}>
                {i > 0 && <span style={{ position: 'absolute', left: 0, top: 10, bottom: 10, width: 1, background: 'rgba(255,255,255,0.12)' }} />}
                <div style={{ fontSize: 8, fontWeight: 800, letterSpacing: '0.06em', color: 'rgba(255,255,255,0.55)', textTransform: 'uppercase' }}>{c[0]}</div>
                <div style={{ fontSize: 13, fontWeight: 800, color: i === 2 ? 'var(--gf-accent)' : '#fff', marginTop: 2 }}>{c[1]}</div>
              </div>
            ))}
          </div>
        </div>

        <div style={{ padding: '16px' }}>
          <div className="gf-acc">
            {blocks.map(b => (
              <AccItem key={b.id} item={b} open={open === b.id} onToggle={() => setOpen(o => o === b.id ? null : b.id)} />
            ))}
          </div>
          <button className="gf-btn gf-btn--ghost" style={{ marginTop: 14 }} onClick={onCarnet}>
            <I.qr /> Ver tarjeta fallera digital
          </button>
        </div>
      </div>

      <BottomNav active="ficha" onNav={onNav} />
    </div>
  );
}

Object.assign(window, { LoginScreen, HomeScreen, FichaScreen });
