// fp-dashboard.jsx — Brand list + creation
// Exports: Dashboard

function Dashboard({ onSelectBrand, onManageUsers }) {
  const { profile, setProfile } = useAuth();
  const isAdmin = profile?.role === 'admin';
  const [brands, setBrands] = useState([]);
  const [loading, setLoading] = useState(true);
  const [showNew, setShowNew] = useState(false);
  const [newName, setNewName] = useState('');
  const [newUsername, setNewUsername] = useState('');
  const [creating, setCreating] = useState(false);

  // Edit own profile
  const [showEditProfile, setShowEditProfile] = useState(false);
  const [editName, setEditName] = useState('');
  const [editPassword, setEditPassword] = useState('');
  const [editPassword2, setEditPassword2] = useState('');
  const [savingProfile, setSavingProfile] = useState(false);
  const [profileMsg, setProfileMsg] = useState({ text: '', ok: true });

  const openEditProfile = () => {
    setEditName(profile?.name || '');
    setEditPassword('');
    setEditPassword2('');
    setProfileMsg({ text: '', ok: true });
    setShowEditProfile(true);
  };

  const saveProfile = async e => {
    e.preventDefault();
    setProfileMsg({ text: '', ok: true });
    if (editPassword && editPassword !== editPassword2) {
      setProfileMsg({ text: 'Las contraseñas no coinciden.', ok: false });
      return;
    }
    setSavingProfile(true);
    if (editName.trim() && editName.trim() !== profile?.name) {
      await sbClient.from('profiles').update({ name: editName.trim() }).eq('id', profile.id);
      setProfile(p => ({ ...p, name: editName.trim() }));
    }
    if (editPassword) {
      const { error } = await sbClient.auth.updateUser({ password: editPassword });
      if (error) {
        setProfileMsg({ text: 'Error al cambiar contraseña: ' + error.message, ok: false });
        setSavingProfile(false);
        return;
      }
    }
    setSavingProfile(false);
    setProfileMsg({ text: '¡Cambios guardados correctamente!', ok: true });
    setEditPassword('');
    setEditPassword2('');
  };

  const loadBrands = async () => {
    setLoading(true);
    let q = sbClient.from('brands').select('*, brand_access(count)').order('created_at', { ascending: false });
    if (!isAdmin) {
      const { data: access } = await sbClient.from('brand_access').select('brand_id').eq('user_id', profile.id);
      const ids = (access || []).map(a => a.brand_id);
      if (!ids.length) { setBrands([]); setLoading(false); return; }
      q = q.in('id', ids);
    }
    const { data } = await q;
    setBrands(data || []);
    setLoading(false);
  };

  useEffect(() => { if (profile) loadBrands(); }, [profile]);

  const createBrand = async e => {
    e.preventDefault();
    if (!newName.trim()) return;
    setCreating(true);
    const { data, error } = await sbClient.from('brands').insert({
      name: newName.trim(),
      username: newUsername.trim() || newName.toLowerCase().replace(/\s+/g,''),
      created_by: profile.id,
    }).select().single();
    if (!error && data) { setBrands(b => [data, ...b]); setShowNew(false); setNewName(''); setNewUsername(''); }
    setCreating(false);
  };

  const deleteBrand = async (id, e) => {
    e.stopPropagation();
    if (!confirm('¿Eliminar esta marca y todos sus posts?')) return;
    await sbClient.from('brands').delete().eq('id', id);
    setBrands(b => b.filter(x => x.id !== id));
  };

  const logout = () => sbClient.auth.signOut();

  return (
    <div style={dbStyles.page}>
      {/* Top bar */}
      <div style={dbStyles.topbar}>
        <div style={dbStyles.logo}>
          <span style={dbStyles.dot}/>Feed Planner
        </div>
        <div style={{display:'flex',alignItems:'center',gap:12}}>
          {isAdmin && (
            <button style={dbStyles.btnOutline} onClick={onManageUsers}>
              <IgIcon name="users" size={16}/> Usuarios
            </button>
          )}
          <div style={{display:'flex',alignItems:'center',gap:8,cursor:'pointer'}} onClick={openEditProfile} title="Editar mi perfil">
            <Avatar name={profile?.name || profile?.email || '?'} size={32}/>
            <div>
              <div style={{fontSize:13,fontWeight:600,lineHeight:1}}>{profile?.name || profile?.email}</div>
              <div style={{fontSize:11,color:'var(--ink-muted)',textTransform:'capitalize'}}>{profile?.role}</div>
            </div>
          </div>
          <button onClick={logout} style={dbStyles.btnIcon} title="Cerrar sesión"><IgIcon name="logout" size={18}/></button>
        </div>
      </div>

      <div style={dbStyles.content}>
        <div style={dbStyles.header}>
          <div>
            <h1 style={dbStyles.title}>Marcas</h1>
            <p style={dbStyles.subtitle}>{brands.length} marca{brands.length !== 1 ? 's' : ''} activa{brands.length !== 1 ? 's' : ''}</p>
          </div>
          {isAdmin && (
            <button style={dbStyles.btnPrimary} onClick={() => setShowNew(true)}>
              <IgIcon name="plus" size={16}/> Nueva marca
            </button>
          )}
        </div>

        {loading ? (
          <div style={{display:'flex',justifyContent:'center',padding:60}}><Spinner size={32}/></div>
        ) : brands.length === 0 ? (
          <div style={dbStyles.empty}>
            <div style={{fontSize:36,marginBottom:12}}>✦</div>
            <p style={{fontWeight:600,marginBottom:4}}>Sin marcas todavía</p>
            {isAdmin && <p style={{color:'var(--ink-muted)',fontSize:13}}>Crea tu primera marca para comenzar</p>}
          </div>
        ) : (
          <div style={dbStyles.grid}>
            {brands.map(b => (
              <div key={b.id} style={dbStyles.card} onClick={() => onSelectBrand(b)}>
                <div style={{...dbStyles.cardColor, background: b.accent_color || 'var(--accent)'}}>
                  {b.avatar_url ? (
                    <img src={b.avatar_url} alt={b.name} style={{width:'100%',height:'100%',objectFit:'cover'}}/>
                  ) : (
                    <span style={{fontFamily:"'Playfair Display',serif",fontSize:28,color:'#fff',fontWeight:600}}>
                      {(b.username || b.name).slice(0,1).toUpperCase()}
                    </span>
                  )}
                </div>
                <div style={dbStyles.cardBody}>
                  <div style={{fontWeight:700,fontSize:15,marginBottom:2}}>{b.name}</div>
                  <div style={{fontSize:12,color:'var(--ink-muted)'}}>@{b.username}</div>
                  {b.bio && <div style={{fontSize:12,color:'var(--ink-soft)',marginTop:6,lineHeight:1.4}}>{b.bio}</div>}
                </div>
                {isAdmin && (
                  <button style={dbStyles.cardDel} onClick={e => deleteBrand(b.id, e)} title="Eliminar marca">
                    <IgIcon name="trash" size={14}/>
                  </button>
                )}
              </div>
            ))}
          </div>
        )}
      </div>

      {/* New brand modal */}
      {showNew && (
        <div style={dbStyles.modalBackdrop} onClick={() => setShowNew(false)}>
          <div style={dbStyles.modalCard} onClick={e => e.stopPropagation()}>
            <h3 style={{fontSize:17,fontWeight:700,marginBottom:16}}>Nueva marca</h3>
            <form onSubmit={createBrand} style={{display:'flex',flexDirection:'column',gap:12}}>
              <div style={dbStyles.field}>
                <label style={dbStyles.fieldLabel}>Nombre de la marca</label>
                <input style={dbStyles.input} type="text" placeholder="Ej. Curly Lab" value={newName} onChange={e=>setNewName(e.target.value)} required autoFocus/>
              </div>
              <div style={dbStyles.field}>
                <label style={dbStyles.fieldLabel}>Usuario de Instagram</label>
                <input style={dbStyles.input} type="text" placeholder="@usuario" value={newUsername} onChange={e=>setNewUsername(e.target.value.replace('@',''))}/>
              </div>
              <div style={{display:'flex',gap:8,marginTop:4}}>
                <button type="submit" style={dbStyles.btnPrimary} disabled={creating}>
                  {creating ? <Spinner size={16} color="#fff"/> : 'Crear marca'}
                </button>
                <button type="button" style={dbStyles.btnOutline} onClick={() => setShowNew(false)}>Cancelar</button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Edit profile modal */}
      {showEditProfile && (
        <div style={dbStyles.modalBackdrop} onClick={() => setShowEditProfile(false)}>
          <div style={dbStyles.modalCard} onClick={e => e.stopPropagation()}>
            <h3 style={{fontSize:17,fontWeight:700,marginBottom:4}}>Mi perfil</h3>
            <p style={{fontSize:12,color:'var(--ink-muted)',marginBottom:16}}>{profile?.email}</p>

            {profileMsg.text && (
              <div style={{background: profileMsg.ok ? 'var(--green-light)' : 'var(--accent-light)', color: profileMsg.ok ? 'var(--green)' : 'var(--accent)', border:'1px solid', borderColor: profileMsg.ok ? 'var(--green)' : 'var(--accent-mid)', borderRadius:9, padding:'9px 12px', fontSize:13, marginBottom:14, lineHeight:1.4}}>
                {profileMsg.text}
              </div>
            )}

            <form onSubmit={saveProfile} style={{display:'flex',flexDirection:'column',gap:12}}>
              <div style={dbStyles.field}>
                <label style={dbStyles.fieldLabel}>Nombre</label>
                <input style={dbStyles.input} type="text" value={editName} onChange={e=>setEditName(e.target.value)} placeholder="Tu nombre"/>
              </div>
              <div style={dbStyles.field}>
                <label style={dbStyles.fieldLabel}>Nueva contraseña</label>
                <input style={dbStyles.input} type="password" value={editPassword} onChange={e=>setEditPassword(e.target.value)} placeholder="Dejar vacío para no cambiar" minLength={6}/>
              </div>
              {editPassword && (
                <div style={dbStyles.field}>
                  <label style={dbStyles.fieldLabel}>Confirmar contraseña</label>
                  <input style={dbStyles.input} type="password" value={editPassword2} onChange={e=>setEditPassword2(e.target.value)} placeholder="Repite la contraseña" minLength={6}/>
                </div>
              )}
              <div style={{display:'flex',gap:8,marginTop:4}}>
                <button type="submit" style={dbStyles.btnPrimary} disabled={savingProfile}>
                  {savingProfile ? <Spinner size={16} color="#fff"/> : 'Guardar cambios'}
                </button>
                <button type="button" style={dbStyles.btnOutline} onClick={() => setShowEditProfile(false)}>Cancelar</button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}

const dbStyles = {
  page:    { minHeight:'100vh', background:'var(--cream)', display:'flex', flexDirection:'column' },
  topbar:  { background:'#fff', borderBottom:'1px solid var(--border)', padding:'14px 32px', display:'flex', alignItems:'center', justifyContent:'space-between' },
  logo:    { fontFamily:"'Playfair Display',serif", fontSize:20, fontWeight:600, display:'flex', alignItems:'center', gap:8 },
  dot:     { width:8, height:8, borderRadius:'50%', background:'var(--accent)', display:'inline-block' },
  content: { flex:1, maxWidth:960, margin:'0 auto', width:'100%', padding:'36px 24px' },
  header:  { display:'flex', alignItems:'flex-end', justifyContent:'space-between', marginBottom:28 },
  title:   { fontFamily:"'Playfair Display',serif", fontSize:28, fontWeight:600, letterSpacing:'-0.5px' },
  subtitle:{ fontSize:13, color:'var(--ink-muted)', marginTop:4 },
  grid:    { display:'grid', gridTemplateColumns:'repeat(auto-fill,minmax(260px,1fr))', gap:16 },
  card:    { background:'#fff', borderRadius:16, overflow:'hidden', cursor:'pointer', boxShadow:'0 1px 4px rgba(28,25,23,0.07)', transition:'all 0.18s', position:'relative' },
  cardColor:{ height:90, display:'flex', alignItems:'center', justifyContent:'center', overflow:'hidden' },
  cardBody:{ padding:'14px 16px 16px' },
  cardDel: { position:'absolute', top:8, right:8, width:28, height:28, background:'rgba(255,255,255,0.85)', border:'none', borderRadius:8, display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer', color:'var(--ink-soft)', opacity:0, transition:'opacity 0.15s' },
  empty:   { textAlign:'center', padding:'80px 24px', color:'var(--ink-soft)' },
  btnPrimary: { background:'var(--accent)', color:'#fff', border:'none', borderRadius:9, padding:'9px 16px', fontFamily:"'DM Sans',sans-serif", fontSize:13, fontWeight:600, cursor:'pointer', display:'flex', alignItems:'center', gap:6 },
  btnOutline: { background:'#fff', color:'var(--ink-soft)', border:'1px solid var(--border)', borderRadius:9, padding:'9px 14px', fontFamily:"'DM Sans',sans-serif", fontSize:13, fontWeight:500, cursor:'pointer', display:'flex', alignItems:'center', gap:6 },
  btnIcon: { background:'none', border:'none', cursor:'pointer', color:'var(--ink-soft)', padding:6, borderRadius:8, display:'flex' },
  modalBackdrop: { position:'fixed', inset:0, background:'rgba(28,25,23,0.45)', display:'flex', alignItems:'center', justifyContent:'center', zIndex:100, backdropFilter:'blur(4px)' },
  modalCard: { background:'#fff', borderRadius:18, padding:'28px 28px 24px', width:380, boxShadow:'0 12px 40px rgba(28,25,23,0.16)' },
  field: { display:'flex', flexDirection:'column', gap:5 },
  fieldLabel: { fontSize:11, fontWeight:600, color:'var(--ink-soft)', letterSpacing:'0.06em', textTransform:'uppercase' },
  input: { background:'var(--cream)', border:'1px solid var(--cream-dark)', borderRadius:8, padding:'9px 12px', fontFamily:"'DM Sans',sans-serif", fontSize:13.5, color:'var(--ink)', outline:'none', width:'100%' },
};

// hover effect via CSS class injection
const dashboardCSS = document.createElement('style');
dashboardCSS.textContent = `.db-card:hover { box-shadow: 0 6px 24px rgba(28,25,23,0.12) !important; transform: translateY(-2px); } .db-card:hover .card-del { opacity: 1 !important; }`;
document.head.appendChild(dashboardCSS);

Object.assign(window, { Dashboard });
