// fp-lib.jsx — Supabase client + shared hooks + UI primitives
// Exports to window: { sbClient, useAuth, useProfile, Spinner, Avatar, IgIcon, TypeIcon, CheckIcon, formatDate, monthKey, monthLabel, MONTH_NAMES, POST_TYPES }

const SUPABASE_URL  = 'https://lcllulljdjhgtbzrovih.supabase.co';
const SUPABASE_ANON = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImxjbGx1bGxqZGpoZ3RienJvdmloIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzY3MTMyMTgsImV4cCI6MjA5MjI4OTIxOH0.oYBQHoTDpAYU7vF5rL1UWlI0X3YWUPI_gekRcTy8i9A';

const { createClient } = window.supabase;
const sbClient = createClient(SUPABASE_URL, SUPABASE_ANON);

const { useState, useEffect, useContext, createContext, useRef, useCallback } = React;

// ── Auth context ──────────────────────────────────────────
const AuthContext = createContext(null);

function AuthProvider({ children }) {
  const [session, setSession] = useState(undefined); // undefined = loading
  const [profile, setProfile] = useState(null);

  useEffect(() => {
    sbClient.auth.getSession().then(({ data }) => setSession(data.session));
    const { data: { subscription } } = sbClient.auth.onAuthStateChange((_e, s) => setSession(s));
    return () => subscription.unsubscribe();
  }, []);

  useEffect(() => {
    if (!session) { setProfile(null); return; }
    sbClient.from('profiles').select('*').eq('id', session.user.id).single()
      .then(({ data }) => setProfile(data));
  }, [session]);

  return <AuthContext.Provider value={{ session, profile, setProfile }}>{children}</AuthContext.Provider>;
}

function useAuth() { return useContext(AuthContext); }

// ── Shared utils ──────────────────────────────────────────
const MONTH_NAMES = ["Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"];
const POST_TYPES  = [
  { id: 'imagen',   label: 'Imagen' },
  { id: 'carrusel', label: 'Carrusel' },
  { id: 'reel',     label: 'Reel' },
];

function monthKey(dateStr) { return dateStr ? dateStr.slice(0,7) : '0000-00'; }
function monthLabel(key) {
  const [y,m] = key.split('-');
  return `${MONTH_NAMES[parseInt(m,10)-1]} ${y}`;
}
function formatDate(str) {
  if (!str) return '';
  const d = new Date(str + 'T12:00:00');
  return d.toLocaleDateString('es-MX', { day:'numeric', month:'short', year:'numeric' });
}

// ── Tiny components ───────────────────────────────────────
function Spinner({ size = 24, color = 'var(--accent)' }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" style={{animation:'spin 0.7s linear infinite'}}>
      <style>{`@keyframes spin{to{transform:rotate(360deg)}}`}</style>
      <circle cx="12" cy="12" r="9" stroke={color} strokeWidth="2.5" strokeDasharray="40 20" strokeLinecap="round"/>
    </svg>
  );
}

function Avatar({ name = '?', size = 36, color = '#C96A42' }) {
  return (
    <div style={{width:size,height:size,borderRadius:'50%',background:color,display:'flex',alignItems:'center',justifyContent:'center',color:'#fff',fontWeight:700,fontSize:size*0.38,flexShrink:0,fontFamily:"'Playfair Display',serif"}}>
      {name.slice(0,1).toUpperCase()}
    </div>
  );
}

function IgIcon({ name, size = 22 }) {
  const icons = {
    home:     <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><path d="M3 9.5L12 3l9 6.5V20a1 1 0 01-1 1H5a1 1 0 01-1-1V9.5z"/><path d="M9 21V12h6v9"/></svg>,
    search:   <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><circle cx="11" cy="11" r="7"/><path d="M21 21l-4.35-4.35"/></svg>,
    add:      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><rect x="3" y="3" width="18" height="18" rx="3"/><path d="M12 8v8M8 12h8"/></svg>,
    reels:    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><rect x="2" y="3" width="20" height="18" rx="2"/><path d="M9 3v18M15 3v18M2 9h20M2 15h20"/></svg>,
    profile:  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><circle cx="12" cy="8" r="4"/><path d="M4 20c0-4 3.6-7 8-7s8 3 8 7"/></svg>,
    grid:     <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/></svg>,
    list:     <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><rect x="3" y="3" width="7" height="18" rx="1"/><rect x="14" y="3" width="7" height="8" rx="1"/><rect x="14" y="15" width="7" height="6" rx="1"/></svg>,
    tag:      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><path d="M20.59 13.41l-7.17 7.17a2 2 0 01-2.83 0L2 12V2h10l8.59 8.59a2 2 0 010 2.82z"/><circle cx="7" cy="7" r="1.5" fill="currentColor"/></svg>,
    more:     <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="5" cy="12" r="1.5" fill="currentColor"/><circle cx="12" cy="12" r="1.5" fill="currentColor"/><circle cx="19" cy="12" r="1.5" fill="currentColor"/></svg>,
    settings: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><circle cx="12" cy="12" r="3"/><path d="M12 2v2M12 20v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M2 12h2M20 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42"/></svg>,
    back:     <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M19 12H5M12 19l-7-7 7-7"/></svg>,
    users:    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><circle cx="9" cy="7" r="4"/><path d="M2 21v-2a4 4 0 014-4h6a4 4 0 014 4v2"/><path d="M19 8v6M22 11h-6" strokeWidth="1.8"/></svg>,
    brand:    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><rect x="3" y="3" width="18" height="18" rx="3"/><path d="M9 9h6M9 12h4M9 15h5"/></svg>,
    trash:    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><path d="M3 6h18M8 6V4h8v2M19 6l-1 14H6L5 6"/><path d="M10 11v5M14 11v5"/></svg>,
    edit:     <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>,
    logout:   <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><path d="M9 21H5a2 2 0 01-2-2V5a2 2 0 012-2h4M16 17l5-5-5-5M21 12H9"/></svg>,
    check:    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M5 13l4 4L19 7"/></svg>,
    plus:     <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 5v14M5 12h14"/></svg>,
    image:    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><path d="M21 15l-5-5L5 21"/></svg>,
  };
  return <span style={{display:'inline-flex',alignItems:'center',width:size,height:size,flexShrink:0}}>{icons[name] || null}</span>;
}

function TypeIcon({ type, size = 14, color = 'white' }) {
  if (type === 'reel') return <svg viewBox="0 0 24 24" fill={color} width={size} height={size}><polygon points="5,3 19,12 5,21"/></svg>;
  if (type === 'carrusel') return <svg viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2.2" width={size} height={size}><rect x="2" y="5" width="13" height="14" rx="2"/><path d="M17 7h2a2 2 0 012 2v8a2 2 0 01-2 2h-2"/></svg>;
  return <svg viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" width={size} height={size}><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><path d="M21 15l-5-5L5 21"/></svg>;
}

function CheckIcon({ size = 10, color = 'white' }) {
  return <svg viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" width={size} height={size}><path d="M5 13l4 4L19 7"/></svg>;
}

Object.assign(window, {
  sbClient, AuthProvider, useAuth,
  Spinner, Avatar, IgIcon, TypeIcon, CheckIcon,
  formatDate, monthKey, monthLabel, MONTH_NAMES, POST_TYPES,
});
