// fp-feed.jsx — Feed Planner with Supabase
// Exports: FeedPlanner

const DEFAULT_CATEGORIES = ["Lifestyle","Producto","Campaña","Educativo","Detrás de cámara","Colab","UGC"];

function FeedPlanner({ brand, onBack }) {
  const { profile } = useAuth();
  const isClient = profile?.role === 'client';
  const canEdit  = !isClient;

  const [posts, setPosts]         = useState([]);
  const [loading, setLoading]     = useState(true);
  const [saving, setSaving]       = useState(false);

  // Form state
  const [form, setForm]           = useState({ imageUrl: null, imageFile: null, date: new Date().toISOString().slice(0,10), category: '', type: 'imagen', copy: '' });
  const [dropOver, setDropOver]   = useState(false);
  const [uploading, setUploading] = useState(false);
  const fileRef                   = useRef();

  // Categories (local per brand, stored in brand row)
  const [categories, setCategories] = useState(brand.categories || DEFAULT_CATEGORIES);
  const [newCat, setNewCat]         = useState('');

  // Brand settings (editable inline)
  const [brandData, setBrandData]   = useState({ ...brand });
  const [editingBrand, setEditingBrand] = useState(false);

  // Brand avatar upload
  const brandAvatarRef = useRef();
  const [uploadingAvatar, setUploadingAvatar] = useState(false);

  const uploadBrandAvatar = async (file) => {
    if (!file || !file.type.startsWith('image/')) return;
    setUploadingAvatar(true);
    const ext = file.name.split('.').pop();
    const path = `brand-avatars/${brand.id}.${ext}`;
    const { error } = await sbClient.storage.from('post-images').upload(path, file, { upsert: true });
    if (error) { alert('Error subiendo imagen: ' + error.message); setUploadingAvatar(false); return; }
    const { data } = sbClient.storage.from('post-images').getPublicUrl(path);
    const avatarUrl = data.publicUrl + '?t=' + Date.now();
    await saveBrandSettings(avatarUrl);
    setUploadingAvatar(false);
  };

  // Detail / edit modal
  const [detail, setDetail]         = useState(null); // post object
  const [editing, setEditing]       = useState(false);
  const [editForm, setEditForm]     = useState({});
  const [detailNotes, setDetailNotes]   = useState('');
  const [detailApproved, setDetailApproved] = useState(false);
  const [editImageFile, setEditImageFile]   = useState(null);

  // Drag
  const [dragSrc, setDragSrc]       = useState(null);
  const [dragTarget, setDragTarget] = useState(null);

  // ── Load posts + brand (to get saved categories) ─────────
  useEffect(() => {
    loadPosts();
    sbClient.from('brands').select('categories, avatar_url').eq('id', brand.id).single().then(({ data }) => {
      if (data) {
        if (Array.isArray(data.categories) && data.categories.length) {
          setCategories(data.categories);
        } else {
          // First time: persist the defaults so future loads work
          sbClient.from('brands').update({ categories: brand.categories || DEFAULT_CATEGORIES }).eq('id', brand.id);
        }
        if (data.avatar_url !== undefined) setBrandData(d => ({ ...d, avatar_url: data.avatar_url }));
      }
    });
  }, [brand.id]);

  const loadPosts = async () => {
    setLoading(true);
    const { data } = await sbClient.from('posts').select('*').eq('brand_id', brand.id).order('order_index').order('created_at', { ascending: false });
    setPosts(data || []);
    setLoading(false);
  };

  // ── Upload image to Supabase Storage ───────────────────
  const uploadImage = async (file) => {
    const ext  = file.name.split('.').pop();
    const path = `${brand.id}/${Date.now()}.${ext}`;
    const { error } = await sbClient.storage.from('post-images').upload(path, file);
    if (error) { alert('Error subiendo imagen: ' + error.message); return null; }
    const { data } = sbClient.storage.from('post-images').getPublicUrl(path);
    return { url: data.publicUrl, path };
  };

  const handleFile = (file) => {
    if (!file || !file.type.startsWith('image/')) return;
    setForm(f => ({ ...f, imageFile: file, imageUrl: URL.createObjectURL(file) }));
  };

  // ── Add post ───────────────────────────────────────────
  const addPost = async () => {
    if (!form.imageFile) return;
    setUploading(true);
    const img = await uploadImage(form.imageFile);
    if (!img) { setUploading(false); return; }
    const maxOrder = posts.length ? Math.max(...posts.map(p => p.order_index || 0)) : 0;
    const { data, error } = await sbClient.from('posts').insert({
      brand_id: brand.id,
      image_url: img.url,
      storage_path: img.path,
      date: form.date,
      category: form.category || 'Sin categoría',
      type: form.type,
      copy: form.copy,
      order_index: maxOrder + 1,
    }).select().single();
    if (!error && data) setPosts(p => [data, ...p]);
    setForm(f => ({ ...f, imageFile: null, imageUrl: null, category: '', copy: '', type: 'imagen' }));
    setUploading(false);
  };

  // ── Delete post ─────────────────────────────────────────
  const deletePost = async (post, e) => {
    e?.stopPropagation();
    if (!confirm('¿Eliminar esta publicación?')) return;
    await sbClient.from('posts').delete().eq('id', post.id);
    if (post.storage_path) await sbClient.storage.from('post-images').remove([post.storage_path]);
    setPosts(p => p.filter(x => x.id !== post.id));
    if (detail?.id === post.id) setDetail(null);
  };

  // ── Open detail modal ───────────────────────────────────
  const openDetail = (post) => {
    setDetail(post);
    setEditing(false);
    setEditForm({ ...post });
    setDetailNotes(post.notes || '');
    setDetailApproved(post.approved || false);
    setEditImageFile(null);
  };

  // ── Save notes/approval (client + editor) ──────────────
  const saveNotes = async () => {
    setSaving(true);
    const updates = { notes: detailNotes, approved: detailApproved };
    await sbClient.from('posts').update(updates).eq('id', detail.id);
    setPosts(ps => ps.map(p => p.id === detail.id ? { ...p, ...updates } : p));
    setDetail(d => ({ ...d, ...updates }));
    setSaving(false);
  };

  // ── Save full post edit ─────────────────────────────────
  const saveEdit = async () => {
    setSaving(true);
    let imageUrl = editForm.image_url;
    let storagePath = editForm.storage_path;
    if (editImageFile) {
      const img = await uploadImage(editImageFile);
      if (img) { imageUrl = img.url; storagePath = img.path; }
    }
    const updates = { ...editForm, image_url: imageUrl, storage_path: storagePath, notes: detailNotes, approved: detailApproved };
    await sbClient.from('posts').update(updates).eq('id', detail.id);
    setPosts(ps => ps.map(p => p.id === detail.id ? updates : p));
    setDetail(updates);
    setEditing(false);
    setSaving(false);
  };

  // ── Save brand settings ────────────────────────────────
  const saveBrandSettings = async (avatarUrl) => {
    const updates = { ...brandData, categories };
    if (avatarUrl !== undefined) updates.avatar_url = avatarUrl;
    await sbClient.from('brands').update(updates).eq('id', brand.id);
    if (avatarUrl !== undefined) setBrandData(d => ({ ...d, avatar_url: avatarUrl }));
    setEditingBrand(false);
  };

  // ── Drag reorder ───────────────────────────────────────
  const handleDropGrid = async (targetId) => {
    if (!dragSrc || dragSrc === targetId) return;
    const arr = [...posts];
    const fi = arr.findIndex(p => p.id === dragSrc);
    const ti = arr.findIndex(p => p.id === targetId);
    const [item] = arr.splice(fi, 1);
    arr.splice(ti, 0, item);
    setPosts(arr);
    setDragSrc(null); setDragTarget(null);
    // persist new order
    await Promise.all(arr.map((p, i) => sbClient.from('posts').update({ order_index: i }).eq('id', p.id)));
  };

  // ── Categories ─────────────────────────────────────────
  const addCategory = () => {
    const c = newCat.trim();
    if (c && !categories.includes(c)) setCategories(cs => [...cs, c]);
    setNewCat('');
  };
  const delCategory = (cat, e) => {
    e.stopPropagation();
    setCategories(cs => cs.filter(c => c !== cat));
    if (form.category === cat) setForm(f => ({ ...f, category: '' }));
  };

  // ── Group by month ─────────────────────────────────────
  const groupedPosts = React.useMemo(() => {
    const groups = {};
    posts.forEach(p => { const k = monthKey(p.date); if (!groups[k]) groups[k] = []; groups[k].push(p); });
    return Object.entries(groups).sort((a, b) => b[0].localeCompare(a[0]));
  }, [posts]);

  const approvedCount = posts.filter(p => p.approved).length;

  return (
    <div className="app" style={{minHeight:"100vh",display:"flex"}}>
      {/* ── SIDEBAR ── */}
      {canEdit && (
        <div className="sidebar" style={{overflowY:"auto",flexShrink:0}}>
          <div className="sidebar-header">
            <button onClick={onBack} style={{background:'none',border:'none',cursor:'pointer',color:'var(--ink-soft)',display:'flex',alignItems:'center',gap:6,fontSize:13,padding:0,marginBottom:12}}>
              <IgIcon name="back" size={16}/> Marcas
            </button>
            <div className="logo">
              <span className="logo-dot" style={{background: brandData.accent_color}}/>
              {brandData.name}
            </div>
            <div style={{display:'flex',gap:8,marginTop:8}}>
              <button className="btn-sm" onClick={() => setEditingBrand(true)}>
                <IgIcon name="edit" size={12}/> Ajustes marca
              </button>
            </div>
          </div>

          <div className="sidebar-body">
            {/* Upload */}
            <div className={`dropzone ${dropOver ? 'drag-over' : ''}`}
              onDragOver={e => { e.preventDefault(); setDropOver(true); }}
              onDragLeave={() => setDropOver(false)}
              onDrop={e => { e.preventDefault(); setDropOver(false); handleFile(e.dataTransfer.files[0]); }}
              onClick={() => !form.imageUrl && fileRef.current.click()}
            >
              <input ref={fileRef} type="file" accept="image/*" style={{display:'none'}} onChange={e => handleFile(e.target.files[0])} />
              {form.imageUrl ? (
                <>
                  <img src={form.imageUrl} className="dropzone-preview" alt="preview"/>
                  <button onClick={e => { e.stopPropagation(); setForm(f=>({...f,imageUrl:null,imageFile:null})); }} style={{marginTop:8,background:'none',border:'1px solid var(--cream-dark)',borderRadius:6,padding:'4px 12px',fontSize:11.5,cursor:'pointer',color:'var(--ink-soft)',width:'100%'}}>✕ Cambiar imagen</button>
                </>
              ) : (
                <>
                  <div className="dropzone-icon">⊕</div>
                  <p><strong>Sube una imagen</strong><br/>Arrastra o haz clic · JPG, PNG, WEBP</p>
                </>
              )}
            </div>

            {/* Type */}
            <div className="field">
              <span className="field-label">Tipo de publicación</span>
              <div className="type-pills">
                {POST_TYPES.map(t => (
                  <div key={t.id} className={`type-pill ${form.type===t.id?'active':''}`} onClick={() => setForm(f=>({...f,type:t.id}))}>
                    <TypeIcon type={t.id} size={12} color={form.type===t.id?'#fff':'currentColor'}/>
                    {t.label}
                  </div>
                ))}
              </div>
            </div>

            <div className="field">
              <span className="field-label">Fecha de publicación</span>
              <input type="date" value={form.date} onChange={e => setForm(f=>({...f,date:e.target.value}))} />
            </div>

            <div className="field">
              <span className="field-label" style={{display:'flex',justifyContent:'space-between'}}>
                Categoría
                <span style={{fontSize:10,color:'var(--ink-muted)',fontWeight:400,textTransform:'none',letterSpacing:0}}>✕ elimina · Enter añade</span>
              </span>
              <div className="chips">
                {categories.map(c => (
                  <div key={c} className={`chip ${form.category===c?'active':''}`} onClick={() => setForm(f=>({...f,category:f.category===c?'':c}))}>
                    {c}<span className="chip-del" onClick={e=>delCategory(c,e)}>✕</span>
                  </div>
                ))}
                <input className="chip-add-input" placeholder="+ Nueva…" value={newCat}
                  onChange={e=>setNewCat(e.target.value)}
                  onKeyDown={e => e.key==='Enter' && addCategory()}
                  onBlur={addCategory}/>
              </div>
            </div>

            <div className="field">
              <span className="field-label">Copy / Caption</span>
              <textarea placeholder="Escribe el texto de tu publicación…" value={form.copy} onChange={e=>setForm(f=>({...f,copy:e.target.value}))} rows={4}/>
            </div>
          </div>

          <div className="sidebar-footer">
            <button className="btn-add" onClick={addPost} disabled={!form.imageUrl || uploading} style={{background: form.imageUrl ? brandData.accent_color : undefined}}>
              {uploading ? <><Spinner size={16} color="#fff"/> Subiendo…</> : '＋ Agregar al feed'}
            </button>
          </div>
        </div>
      )}

      {/* ── MAIN ── */}
      <div className="main" style={{overflowY:"auto",flex:1}}>
        <div className="main-top">
          {isClient && (
            <button onClick={onBack} style={{background:'none',border:'none',cursor:'pointer',color:'var(--ink-soft)',display:'flex',alignItems:'center',gap:6,fontSize:13,padding:0}}>
              <IgIcon name="back" size={16}/> Inicio
            </button>
          )}
          <span style={{fontSize:12,color:'var(--ink-muted)'}}>
            <strong style={{color:'var(--ink)'}}>{posts.length}</strong> publicaciones
            {approvedCount > 0 && <span style={{marginLeft:8,background:'var(--green-light)',color:'var(--green)',fontSize:11,fontWeight:600,padding:'2px 8px',borderRadius:20}}>✓ {approvedCount} aprobadas</span>}
          </span>
          {canEdit && posts.length > 0 && <button className="btn-sm" onClick={() => { if(confirm('¿Limpiar todo el feed?')) { posts.forEach(p => deletePost(p)); } }}>Limpiar feed</button>}
        </div>

        <div className="phone-wrapper">
          <div className="status-bar">
            <span className="time">9:41</span>
            <div className="icons">
              <svg viewBox="0 0 24 24" width="16" height="16"><path d="M1.5 8.5C5.2 4.8 9.4 3 12 3s6.8 1.8 10.5 5.5M4.5 11.5C7.2 8.8 9.8 7 12 7s4.8 1.8 7.5 4.5M7.5 14.5C9.2 12.8 10.7 12 12 12s2.8.8 4.5 2.5M12 17.5v.5" strokeWidth="1.5" stroke="currentColor" fill="none"/></svg>
              <svg viewBox="0 0 24 24" width="16" height="16"><rect x="2" y="7" width="16" height="10" rx="2" stroke="currentColor" strokeWidth="1.5" fill="none"/><path d="M20 10v4" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/></svg>
            </div>
          </div>

          <div className="ig-header">
            <span className="ig-username">{brandData.username || brandData.name}
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" style={{width:13,height:13,marginLeft:4,verticalAlign:'middle',opacity:.4}}><path d="M6 9l6 6 6-6"/></svg>
            </span>
            <div className="ig-header-icons"><IgIcon name="more" size={20}/><IgIcon name="settings" size={20}/></div>
          </div>

          <div className="ig-profile">
            <div className="ig-profile-top">
              <div className="ig-avatar" style={{boxShadow:`0 0 0 2px ${brandData.accent_color}`, overflow:'hidden', padding:0, display:'flex', alignItems:'center', justifyContent:'center'}}>
                {brandData.avatar_url
                  ? <img src={brandData.avatar_url} alt="avatar" style={{width:'100%',height:'100%',objectFit:'cover'}}/>
                  : (brandData.username||brandData.name).slice(0,1).toUpperCase()
                }
              </div>
              <div className="ig-stats">
                <div className="ig-stat"><span className="ig-stat-n">{posts.length}</span><span className="ig-stat-l">publicaciones</span></div>
                <div className="ig-stat"><span className="ig-stat-n">—</span><span className="ig-stat-l">seguidores</span></div>
                <div className="ig-stat"><span className="ig-stat-n">—</span><span className="ig-stat-l">seguidos</span></div>
              </div>
            </div>
            <div className="ig-bio-name" style={{color: brandData.accent_color}}>{brandData.username || brandData.name}</div>
            {brandData.bio && <div className="ig-bio-text">{brandData.bio}</div>}
          </div>

          {brandData.show_highlights && (
            <div className="ig-highlights">
              {["✦","🎨","🛍️","📍","💬"].map((icon,i) => (
                <div className="highlight-item" key={i}>
                  <div className="highlight-circle" style={{borderColor: brandData.accent_color+'60'}}>{icon}</div>
                  <span className="highlight-label">Story</span>
                </div>
              ))}
            </div>
          )}

          <div className="ig-tabs">
            <div className="ig-tab active"><IgIcon name="grid" size={20}/></div>
            <div className="ig-tab" style={{color:'var(--ink-muted)'}}><IgIcon name="list" size={20}/></div>
            <div className="ig-tab" style={{color:'var(--ink-muted)'}}><IgIcon name="tag" size={20}/></div>
          </div>

          <div className="ig-grid">
            {loading ? (
              <div style={{gridColumn:'1/-1',padding:40,display:'flex',justifyContent:'center',background:'#fff'}}><Spinner/></div>
            ) : posts.length === 0 ? (
              <div className="grid-placeholder">
                <p className="big">✦</p>
                <p>Feed vacío.{canEdit ? ' Agrega publicaciones desde el panel.' : ''}</p>
              </div>
            ) : groupedPosts.map(([mk, mPosts]) => (
              <React.Fragment key={mk}>
                <div className="month-divider">
                  <span className="month-divider-label">{monthLabel(mk)}</span>
                  <span className="month-divider-line"/>
                  <span className="month-divider-count">{mPosts.length} post{mPosts.length!==1?'s':''} · {mPosts.filter(p=>p.approved).length} ✓</span>
                </div>
                {mPosts.map(post => (
                  <div key={post.id}
                    className={`post-cell ${dragSrc===post.id?'dragging':''} ${dragTarget===post.id&&dragSrc!==post.id?'drag-target':''}`}
                    draggable={canEdit}
                    onDragStart={() => setDragSrc(post.id)}
                    onDragEnd={() => { setDragSrc(null); setDragTarget(null); }}
                    onDragEnter={() => setDragTarget(post.id)}
                    onDragOver={e => e.preventDefault()}
                    onDrop={() => handleDropGrid(post.id)}
                    onClick={() => openDetail(post)}
                  >
                    <img src={post.image_url} alt="" loading="lazy"/>
                    {post.type !== 'imagen' && <div className="post-type-badge"><TypeIcon type={post.type} size={16}/></div>}
                    <div className={`post-approved-badge ${post.approved?'visible':''}`}><CheckIcon size={9}/></div>
                    <div className="post-cell-overlay">
                      {post.category && <span className="post-cell-category">{post.category}</span>}
                      <span className="post-cell-date">{formatDate(post.date)}</span>
                      {post.copy && <span className="post-cell-copy">{post.copy}</span>}
                    </div>
                    {canEdit && <button className="post-cell-del" onClick={e => deletePost(post, e)}>✕</button>}
                  </div>
                ))}
              </React.Fragment>
            ))}
          </div>

          <div className="ig-bottom-nav">
            {['home','search','add','reels','profile'].map(n => (
              <div className="ig-nav-item" key={n} style={{color:n==='profile'?'var(--ink)':'var(--ink-muted)'}}><IgIcon name={n} size={22}/></div>
            ))}
          </div>
        </div>
        <div style={{height:40}}/>
      </div>

      {/* ── DETAIL MODAL ── */}
      {detail && (
        <div className="modal-backdrop" onClick={() => setDetail(null)}>
          <div className="modal-card" onClick={e => e.stopPropagation()}>
            {/* Image + edit image */}
            <div style={{position:'relative'}}>
              <img src={editing && editImageFile ? URL.createObjectURL(editImageFile) : detail.image_url} className="modal-img" alt=""/>
              {editing && canEdit && (
                <label style={{position:'absolute',bottom:10,right:10,background:'rgba(0,0,0,0.6)',color:'#fff',borderRadius:8,padding:'6px 12px',fontSize:12,fontWeight:600,cursor:'pointer',display:'flex',alignItems:'center',gap:5}}>
                  <IgIcon name="image" size={13}/> Cambiar
                  <input type="file" accept="image/*" style={{display:'none'}} onChange={e => setEditImageFile(e.target.files[0])}/>
                </label>
              )}
            </div>

            <div className="modal-body">
              {/* Header row */}
              <div className="modal-row">
                {editing ? (
                  <>
                    <select value={editForm.category} onChange={e=>setEditForm(f=>({...f,category:e.target.value}))} style={{fontSize:12,border:'1px solid var(--cream-dark)',borderRadius:8,padding:'4px 8px',background:'var(--cream)',fontFamily:'inherit',outline:'none'}}>
                      {categories.map(c => <option key={c}>{c}</option>)}
                    </select>
                    <select value={editForm.type} onChange={e=>setEditForm(f=>({...f,type:e.target.value}))} style={{fontSize:12,border:'1px solid var(--cream-dark)',borderRadius:8,padding:'4px 8px',background:'var(--cream)',fontFamily:'inherit',outline:'none'}}>
                      {POST_TYPES.map(t => <option key={t.id} value={t.id}>{t.label}</option>)}
                    </select>
                    <input type="date" value={editForm.date} onChange={e=>setEditForm(f=>({...f,date:e.target.value}))} style={{fontSize:12,border:'1px solid var(--cream-dark)',borderRadius:8,padding:'4px 8px',background:'var(--cream)',fontFamily:'inherit',outline:'none'}}/>
                  </>
                ) : (
                  <>
                    <span className="modal-cat">{detail.category}</span>
                    <span className="modal-type">{POST_TYPES.find(t=>t.id===detail.type)?.label}</span>
                    <span className="modal-date">{formatDate(detail.date)}</span>
                  </>
                )}
              </div>

              {/* Copy */}
              {editing ? (
                <textarea className="modal-notes" value={editForm.copy} onChange={e=>setEditForm(f=>({...f,copy:e.target.value}))} placeholder="Caption…" rows={3}/>
              ) : (
                detail.copy && <p className="modal-copy">{detail.copy}</p>
              )}

              {/* Notes */}
              <div className="modal-section">
                <span className="modal-section-label">Notas del cliente</span>
                <textarea className="modal-notes" placeholder="Escribe el feedback aquí…" value={detailNotes} onChange={e => setDetailNotes(e.target.value)} rows={3}/>
              </div>

              {/* Approval */}
              <div className={`modal-approved-row ${detailApproved?'approved':''}`} onClick={() => setDetailApproved(v=>!v)}>
                <div className="modal-approved-check">{detailApproved && <CheckIcon size={10}/>}</div>
                <span className="modal-approved-label">{detailApproved ? '✓ Publicación aprobada' : 'Marcar como aprobada'}</span>
              </div>

              {/* Actions */}
              <div className="modal-actions">
                {editing ? (
                  <>
                    <button className="modal-btn-save" onClick={saveEdit} style={{background: brandData.accent_color}}>
                      {saving ? <Spinner size={16} color="#fff"/> : 'Guardar cambios'}
                    </button>
                    <button className="modal-btn-close" onClick={() => setEditing(false)}>Cancelar</button>
                  </>
                ) : (
                  <>
                    <button className="modal-btn-save" onClick={saveNotes} style={{background: brandData.accent_color}}>
                      {saving ? <Spinner size={16} color="#fff"/> : 'Guardar notas'}
                    </button>
                    {canEdit && <button className="modal-btn-close" onClick={() => setEditing(true)} style={{display:'flex',alignItems:'center',gap:5}}><IgIcon name="edit" size={14}/>Editar</button>}
                    {canEdit && <button className="modal-btn-close" onClick={() => deletePost(detail)} style={{color:'#C0392B'}}><IgIcon name="trash" size={14}/></button>}
                    <button className="modal-btn-close" onClick={() => setDetail(null)}>✕</button>
                  </>
                )}
              </div>
            </div>
          </div>
        </div>
      )}

      {/* ── BRAND SETTINGS MODAL ── */}
      {editingBrand && (
        <div className="modal-backdrop" onClick={() => setEditingBrand(false)}>
          <div className="modal-card" onClick={e=>e.stopPropagation()} style={{maxHeight:'90vh',overflowY:'auto'}}>
            <div style={{padding:'20px 20px 0',fontWeight:700,fontSize:16}}>Ajustes de la marca</div>
            <div className="modal-body">
              {/* Brand avatar */}
              <div className="modal-section">
                <span className="modal-section-label">Foto de perfil</span>
                <div style={{display:'flex',alignItems:'center',gap:12}}>
                  <div style={{width:56,height:56,borderRadius:'50%',overflow:'hidden',background:'var(--cream)',border:'2px solid var(--cream-dark)',display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0,fontSize:22,fontWeight:700,color:brandData.accent_color}}>
                    {brandData.avatar_url
                      ? <img src={brandData.avatar_url} alt="avatar" style={{width:'100%',height:'100%',objectFit:'cover'}}/>
                      : (brandData.username||brandData.name||'?').slice(0,1).toUpperCase()
                    }
                  </div>
                  <div style={{display:'flex',flexDirection:'column',gap:6}}>
                    <label style={{background:'var(--cream)',border:'1px solid var(--cream-dark)',borderRadius:8,padding:'7px 12px',fontSize:12,fontWeight:600,cursor:'pointer',display:'flex',alignItems:'center',gap:6,color:'var(--ink-soft)'}}>
                      <IgIcon name="image" size={13}/> {uploadingAvatar ? 'Subiendo...' : 'Cambiar foto'}
                      <input ref={brandAvatarRef} type="file" accept="image/*" style={{display:'none'}} onChange={e=>uploadBrandAvatar(e.target.files[0])} disabled={uploadingAvatar}/>
                    </label>
                    {brandData.avatar_url && (
                      <button onClick={()=>saveBrandSettings(null)} style={{background:'none',border:'none',fontSize:11,color:'var(--ink-muted)',cursor:'pointer',textAlign:'left',padding:0}}>Quitar foto</button>
                    )}
                  </div>
                </div>
              </div>
              {[['name','Nombre'],['username','Usuario de Instagram'],['bio','Bio']].map(([k,l]) => (
                <div key={k} className="modal-section">
                  <span className="modal-section-label">{l}</span>
                  <input type="text" className="modal-notes" style={{minHeight:'auto',resize:'none'}} value={brandData[k]||''} onChange={e=>setBrandData(d=>({...d,[k]:e.target.value}))}/>
                </div>
              ))}
              <div className="modal-section">
                <span className="modal-section-label">Color acento</span>
                <input type="color" value={brandData.accent_color||'#C96A42'} onChange={e=>setBrandData(d=>({...d,accent_color:e.target.value}))} style={{width:'100%',height:36,border:'1px solid var(--cream-dark)',borderRadius:8,cursor:'pointer'}}/>
              </div>
              <div className="modal-section">
                <span className="modal-section-label" style={{display:'flex',alignItems:'center',gap:8}}>
                  <input type="checkbox" checked={brandData.show_highlights} onChange={e=>setBrandData(d=>({...d,show_highlights:e.target.checked}))}/>
                  Mostrar Highlights
                </span>
              </div>
              <div className="modal-actions">
                <button className="modal-btn-save" onClick={() => saveBrandSettings()} style={{background: brandData.accent_color}}>Guardar</button>
                <button className="modal-btn-close" onClick={() => setEditingBrand(false)}>Cancelar</button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { FeedPlanner });
