const { useState, useMemo, useEffect } = React;

// ─── POSTHOG ANALYTICS ────────────────────────────────────────────────────────
const PH_KEY  = "phc_zHDwqePS32GNLakHbT95tmirBLBY37Ah8tvvD8ohgWbS";
const PH_HOST = "https://eu.i.posthog.com";

function phCapture(event, props={}) {
  try { if (window.posthog) window.posthog.capture(event, props); } catch(e) {}
}

function initPostHog() {
  if (window.posthog && window.posthog.__loaded) return;
  const script = document.createElement("script");
  script.src = "https://eu-assets.i.posthog.com/static/array.js";
  script.async = true;
  script.onload = () => {
    window.posthog.init(PH_KEY, {
      api_host: PH_HOST,
      person_profiles: "identified_only",
      capture_pageview: false,
      autocapture: false,
    });
    window.posthog.capture("app_opened");
  };
  document.head.appendChild(script);
}

// ─── DATE ─────────────────────────────────────────────────────────────────────
function getDateContext() {
  const now = new Date();
  const m = now.getMonth();
  const y = now.getFullYear();
  const months = ["ianuarie","februarie","martie","aprilie","mai","iunie","iulie","august","septembrie","octombrie","noiembrie","decembrie"];
  const sezon = m>=2&&m<=4?"primavara":m>=5&&m<=7?"vara":m>=8&&m<=10?"toamna":"iarna";
  return { luna:months[m], an:y, sezon, complet:months[m]+" "+y };
}

// ─── DATA ─────────────────────────────────────────────────────────────────────
const ALL_BIZ = [
  // Marketing & Media
  "Agentie Marketing","Agentie Publicitate","Agentie Social Media","Agentie PR","Agentie Branding",
  "Agentie Imobiliara","Agentie Turism","Agentie Evenimente","Agentie Recrutare","Agentie Modeling",
  "Studio Foto","Studio Video","Studio Podcast","Studio Muzica","Creator de Continut","Influencer",
  // Auto
  "Auto Service","Dealer Auto","Spalatorie Auto","Rent a Car","Tuning Auto","Piese Auto",
  "Vulcanizare","Inchirieri Auto","Transport Persoane","Taxi Ridesharing",
  // Food & Drink
  "Bistro","Restaurant Traditional","Restaurant International","Fast Food","Pizzerie","Burgerie",
  "Sushi","Shawarma","Taverna","Cafenea","Ceainarie","Juice Bar","Smoothie Bar","Coffee Shop",
  "Patiserie","Brutarie","Cofetarie","Croissanterie","Waffle Bar","Donut Shop",
  "Bar Pub","Club de Noapte","Lounge Bar","Sky Bar","Wine Bar","Bere Artizanala",
  "Food Truck","Catering","Chef Personal","Livrare Mancare",
  // Beauty & Wellness
  "Salon Coafura Femei","Salon Coafura Barbati","Frizerie Barbershop","Salon Unghii",
  "Salon Infrumusetare","Salon Sprancene","Salon Extensii Gene","Salon Tatuaje","Salon Piercing",
  "Salon Masaj","SPA Wellness","Epilare Definitiva Laser","Bronzare Solarium","Crioterapie",
  "Make-up Artist","Manichiura Pedichiura","Microblading","Dermato-Cosmetica",
  // Fitness & Sport
  "Sala Fitness Gym","Sala Yoga","Sala Pilates","Sala Dans","CrossFit","Box Arte Martiale",
  "Personal Trainer","Nutritionist","Dietitian","Sala Kickbox","Sala Lupte","Sala Inot",
  "Teren Padel","Sala Squash","Climbing Wall","Studio Zumba","Bootcamp Outdoor",
  // Sanatate & Medical
  "Clinica Stomatologica","Cabinet Medical","Clinica Dermatologie","Clinica Estetica",
  "Fizioterapie","Farmacie","Cabinet Psihologie","Cabinet Veterinar","Clinica Oftalmologie",
  "Clinica Ortopedie","Cabinet Nutritie","Centru Recuperare","Laborator Analize","Clinica Laser",
  // Retail & Fashion
  "Magazin Online","Magazin Haine","Magazin Pantofi","Magazin Electronice","Magazin Sport",
  "Magazin Bijuterii","Magazin Cosmetice","Magazin Cadouri","Magazin Copii","Magazin Animale",
  "Magazin Carte","Magazin Muzica","Magazin Jucarii","Magazin Articole Casa","Magazin Gradina",
  "Magazin Biciclete","Magazin Camping","Magazin Pescuit","Boutique Moda","Vintage Shop",
  "Thrift Store","Magazin Handmade","Artizanat","Galerie Arta",
  // Hospitality & Travel
  "Hotel Resort","Pensiune","Hostel","Vila Vacanta","Apartament Airbnb","Casa de Vacanta",
  "Camping Glamping","Cabana Munte","Agentie Vacante","Turism Rural","Ecoturism",
  // Events & Entertainment
  "Sala Evenimente Nunta","Sala Conferinte","Escape Room","Bowling","Karting","Laser Tag",
  "Fotograf Nunta","Fotograf Comercial","Videograf","DJ Muzica Live","Trupa Muzica",
  "Animator Copii","Magician","Majorete","Servicii Nunta Complet","Florarie","Decorator Evenimente",
  "Organizator Evenimente","Rentals Evenimente","Photo Booth","Artificii",
  // Constructii & Casa
  "Constructii Renovari","Instalatii Sanitare","Instalatii Electrice","Electrician",
  "Tamplarie PVC Aluminiu","Tamplarie Lemn","Geamuri Termopan","Acoperisuri","Fatade",
  "Amenajari Interioare","Design Interior","Mobila la Comanda","Mobila Bucatarie",
  "Covoare Parchet","Gresie Faianta","Vopsitorie","Constructii Piscine","Peisagistica",
  "Gradinarit","Servicii Curatenie","Curatenie Profesionala","Pest Control",
  // Education & Coaching
  "Coaching Business","Coaching Personal","Life Coaching","Coaching Sportiv",
  "Cursuri Online","Scoala Privata","Gradinita After School","Meditatii","Scoala Soferi",
  "Cursuri Limbi Straine","Cursuri IT Programare","Cursuri Design","Cursuri Marketing",
  "Cursuri Coafura","Cursuri Make-up","Cursuri Patiserie","Cursuri Dans",
  // Tech & Digital
  "IT Software","Web Design","Dezvoltare Aplicatii","SEO Digital Marketing","Email Marketing",
  "E-commerce","Cybersecurity","Cloud Services","AI Automation","Video Productie",
  // Professional Services
  "Consultanta Business","Avocatura","Notariat","Contabilitate Taxe","Audit Financiar",
  "Asigurari","Broker Credite","Broker Imobiliar","Transport Curierat","Logistica Depozitare",
  "Servicii Traduceri","Servicii Secretariat","Resurse Umane","Headhunting",
  // Animale
  "Pet Shop","Salon Grooming Animale","Clinica Veterinara","Pensiune Animale","Dog Training",
  "Acvariu","Magazin Acvaristika",
  // Altele
  "Imprimerie Tipar","Laser Gravura","Productie Publicitara","Signaletică","Broderie Personalizare",
  "Producator Alimente","Apicultura Miere","Ferma","Distributie Angro","Altul",
];

const ALL_CITIES = [
  "National (toata Romania)","International",
  "Bucuresti","Cluj-Napoca","Timisoara","Iasi","Brasov","Constanta","Craiova","Galati",
  "Ploiesti","Oradea","Braila","Arad","Pitesti","Sibiu","Bacau","Targu Mures","Baia Mare",
  "Buzau","Botosani","Satu Mare","Ramnicu Valcea","Drobeta-Turnu Severin","Suceava",
  "Piatra Neamt","Targu Jiu","Tulcea","Focsani","Bistrita","Resita","Alba Iulia","Deva",
  "Sfantu Gheorghe","Zalau","Vaslui","Alexandria","Calarasi","Giurgiu","Dej","Lugoj",
  "Medias","Onesti","Roman","Turda","Petrosani","Slatina","Slobozia","Targoviste",
  "Tecuci","Ramnicu Sarat","Mangalia","Curtea de Arges","Fagaras","Campina","Sinaia","Predeal",
];

const TONES     = ["Energic","Profesional","Amuzant","Inspirational","Dramatic","Sincer"];
const PLATFORMS = ["TikTok","Instagram Reels","YouTube Shorts","Facebook Reels"];
const DURATIONS = ["15 sec","30 sec","60 sec","15-30 sec","30-60 sec","60-90 sec"];

const TEMPLATES = [
  { id:"generic",  icon:"✨", label:"Generic",         desc:"Script complet personalizat" },
  { id:"poveste",  icon:"❤️", label:"Poveste client",  desc:"Transformare emotionanta" },
  { id:"pov",      icon:"👁",  label:"POV",             desc:"Perspectiva clientului" },
  { id:"3greseli", icon:"⚠️", label:"3 Greseli",       desc:"Educi si atragi atentia" },
  { id:"inainte",  icon:"🔄", label:"Inainte / Dupa",  desc:"Transformare vizuala" },
  { id:"mit",      icon:"💥", label:"Mit vs Realitate", desc:"Sparge asteptarile" },
  { id:"reactie",  icon:"😮", label:"Reactie client",   desc:"Social proof organic" },
  { id:"trend",    icon:"🔥", label:"Trend adaptat",    desc:"Trend viral adaptat" },
];

const NAV = [
  { id:"gen",      icon:"⚡", label:"Generator" },
  { id:"hook",     icon:"🎯", label:"Hook"      },
  { id:"video",    icon:"🎬", label:"Video"     },
  { id:"trend",    icon:"🔥", label:"Trenduri"  },
  { id:"cal",      icon:"📅", label:"Calendar"  },
  { id:"story",    icon:"📸", label:"Stories"   },
  { id:"cre",      icon:"🌟", label:"Creatori"  },
  { id:"hist",     icon:"🗂",  label:"Istoric"   },
  { id:"feedback", icon:"💬", label:"Feedback"  },
  { id:"despre",   icon:"ℹ️",  label:"Despre"    },
  { id:"help",     icon:"❓", label:"Ghid"      },
  { id:"profil",   icon:"👤", label:"Profil"    },
];

// ─── THEME ────────────────────────────────────────────────────────────────────
const DARK = {
  bg:"#080810",
  top:"rgba(12,12,20,0.92)",
  card:"#12121e",
  bord:"#1e1e30",
  acc:"#7c6df0",
  acc2:"#a78bfa",
  pink:"#f472b6",
  teal:"#34d4c4",
  gold:"#fbbf24",
  green:"#4ade80",
  red:"#fb7185",
  txt:"#ede9fe",
  txt2:"#8b8aac",
  muted:"#44445a",
  faint:"#0d0d1a",
  shadow:"rgba(0,0,0,0.6)",
  glow:"rgba(124,109,240,0.15)",
};
const LIGHT = {
  bg:"#f0effc",
  top:"rgba(255,255,255,0.94)",
  card:"#ffffff",
  bord:"#e2e0f5",
  acc:"#6d5ef0",
  acc2:"#8b5cf6",
  pink:"#ec4899",
  teal:"#0d9488",
  gold:"#d97706",
  green:"#16a34a",
  red:"#e11d48",
  txt:"#16103a",
  txt2:"#4a4470",
  muted:"#9490b8",
  faint:"#eceaf8",
  shadow:"rgba(109,94,240,0.10)",
  glow:"rgba(109,94,240,0.08)",
};

// ─── ACCENT COLORS ────────────────────────────────────────────────────────────
const ACCENTS = [
  { id:"violet", label:"Violet",  dark:"#7c6df0", dark2:"#a78bfa", light:"#6d5ef0", light2:"#8b5cf6" },
  { id:"albastru",label:"Albastru",dark:"#3b82f6", dark2:"#60a5fa", light:"#2563eb", light2:"#3b82f6" },
  { id:"verde",  label:"Verde",   dark:"#10b981", dark2:"#34d399", light:"#059669", light2:"#10b981" },
  { id:"rosu",   label:"Roz",     dark:"#f472b6", dark2:"#f9a8d4", light:"#ec4899", light2:"#f472b6" },
  { id:"portocaliu",label:"Portocaliu",dark:"#f97316",dark2:"#fb923c",light:"#ea580c",light2:"#f97316"},
];

// ─── THEME BUILDER ─────────────────────────────────────────────────────────────
function buildTheme(dark, accentId) {
  const a = ACCENTS.find(x=>x.id===accentId) || ACCENTS[0];
  const acc  = dark ? a.dark  : a.light;
  const acc2 = dark ? a.dark2 : a.light2;
  if (dark) return { ...DARK, acc, acc2 };
  return { ...LIGHT, acc, acc2 };
}
// ─── CLOUDFLARE WORKER PROXY ─────────────────────────────────────────────────
const WORKER_URL = "https://creavo-api.davidvirtan.workers.dev";

async function callAI(prompt, retries=2) {
  for (let i=0; i<=retries; i++) {
    try {
      const ctrl = new AbortController();
      const t = setTimeout(()=>ctrl.abort(), 45000);
      const res = await fetch(WORKER_URL, {
        method:"POST",
        headers:{"Content-Type":"application/json"},
        signal:ctrl.signal,
        body:JSON.stringify({ prompt }),
      });
      clearTimeout(t);
      if (!res.ok) throw new Error("Server "+res.status);
      const d = await res.json();
      if (d.error) throw new Error(d.error.message||d.error);
      const raw = (d.content||[]).filter(b=>b.type==="text").map(b=>b.text||"").join("");
      if (!raw.trim()) throw new Error("Răspuns gol. Încearcă din nou.");
      const s=raw.indexOf("{"), e=raw.lastIndexOf("}");
      if (s===-1||e===-1) throw new Error("Format invalid. Încearcă din nou.");
      return JSON.parse(raw.slice(s,e+1));
    } catch(err) {
      if (err.name==="AbortError") throw new Error("Timeout — conexiune lentă. Încearcă din nou.");
      if (i===retries) throw new Error(err.message||"Eroare. Încearcă din nou.");
      await new Promise(r=>setTimeout(r,1500*(i+1)));
    }
  }
}

// ─── STORAGE ──────────────────────────────────────────────────────────────────
const LS = {
  get:(k,fb)=>{ try{const v=localStorage.getItem(k);return v?JSON.parse(v):fb;}catch{return fb;} },
  set:(k,v)=>{ try{localStorage.setItem(k,JSON.stringify(v));}catch{} },
};

// ─── SHARED UI ────────────────────────────────────────────────────────────────
const LOADER_MSGS = [
  "Analizez trendurile actuale...",
  "Scriu hook-ul perfect...",
  "Optimizez pentru platforma ta...",
  "Adaug detalii specifice...",
  "Finalizez scriptul...",
  "Verific calitatea continutului...",
];

function Dots({label,T}) {
  const [msgIdx, setMsgIdx] = useState(0);
  useEffect(() => {
    const interval = setInterval(() => {
      setMsgIdx(i => (i + 1) % LOADER_MSGS.length);
    }, 2800);
    return () => clearInterval(interval);
  }, []);

  const displayMsg = label || LOADER_MSGS[msgIdx];

  return (
    <div style={{textAlign:"center",padding:"70px 24px"}}>
      {/* Animated logo icon */}
      <div style={{
        width:"64px",height:"64px",borderRadius:"20px",
        background:"#0f0d1e",
        margin:"0 auto 24px",
        display:"flex",alignItems:"center",justifyContent:"center",
        position:"relative",
        boxShadow:`0 8px 32px ${T.acc}40`,
        animation:"vcpulse 2s ease-in-out infinite",
      }}>
        <svg width="38" height="38" viewBox="0 0 38 38" xmlns="http://www.w3.org/2000/svg">
          <defs>
            <linearGradient id="lg_loader" x1="0%" y1="0%" x2="100%" y2="100%">
              <stop offset="0%" stopColor="#7c6df0"/>
              <stop offset="100%" stopColor="#f472b6"/>
            </linearGradient>
          </defs>
          <rect x="7" y="26" width="5" height="8" rx="1.5" fill="url(#lg_loader)" opacity="0.5"/>
          <rect x="15" y="19" width="5" height="15" rx="1.5" fill="url(#lg_loader)" opacity="0.75"/>
          <rect x="23" y="12" width="5" height="22" rx="1.5" fill="url(#lg_loader)"/>
          <circle cx="31" cy="8" r="2" fill="#f472b6" opacity="0.9"/>
        </svg>
      </div>

      {/* Dots */}
      <div style={{display:"flex",justifyContent:"center",gap:"8px",marginBottom:"20px"}}>
        {[0,1,2].map(i=>(
          <div key={i} style={{
            width:"8px",height:"8px",borderRadius:"50%",
            background:`linear-gradient(135deg,${T.acc},${T.pink})`,
            animation:`vcdot 1.2s ${i*0.2}s ease-in-out infinite`,
          }}/>
        ))}
      </div>

      {/* Rotating message */}
      <p style={{
        color:T.txt2,fontSize:"14px",margin:"0 0 8px",
        fontWeight:600,lineHeight:1.5,
        animation:"vcfade 0.4s ease",
        key:msgIdx,
      }}>{LOADER_MSGS[msgIdx]}</p>

      {/* Static context label */}
      {label && (
        <p style={{color:T.muted,fontSize:"12px",margin:0,lineHeight:1.5}}>{label}</p>
      )}

      <style>{`
        @keyframes vcdot{0%,80%,100%{transform:scale(0.35);opacity:0.2}40%{transform:scale(1.1);opacity:1}}
        @keyframes vcpulse{0%,100%{box-shadow:0 8px 32px ${T.acc}40}50%{box-shadow:0 8px 48px ${T.acc}70}}
        @keyframes vcfade{from{opacity:0;transform:translateY(4px)}to{opacity:1;transform:translateY(0)}}
      `}</style>
    </div>
  );
}

function ErrBox({msg,retry,T}) {
  return (
    <div style={{
      padding:"14px 18px",marginTop:"12px",borderRadius:"16px",
      background:`${T.red}12`,
      border:`1px solid ${T.red}35`,
      display:"flex",justifyContent:"space-between",alignItems:"center",gap:"12px",
      boxShadow:`0 4px 16px ${T.red}15`,
    }}>
      <span style={{color:T.red,fontSize:"13px",lineHeight:1.4,fontWeight:500}}>⚠️ {msg}</span>
      {retry&&(
        <button onClick={retry} style={{
          padding:"7px 16px",borderRadius:"10px",
          border:`1px solid ${T.red}50`,
          background:`${T.red}15`,color:T.red,
          fontSize:"12px",cursor:"pointer",fontFamily:"inherit",
          flexShrink:0,fontWeight:600,
        }}>Retry</button>
      )}
    </div>
  );
}

function Lbl({color,children}) {
  return <div style={{
    fontSize:"13px",fontWeight:800,letterSpacing:"0.5px",
    color,marginBottom:"10px",
  }}>{children}</div>;
}

function CBtn({text,label="Copiază",T}) {
  const [ok,setOk]=useState(false);
  return (
    <button onClick={()=>{navigator.clipboard.writeText(text||"");setOk(true);setTimeout(()=>setOk(false),2000);}}
      style={{
        padding:"8px 18px",borderRadius:"10px",
        border:`1px solid ${ok ? T.green+"80" : T.bord}`,
        background:ok ? `${T.green}18` : T.faint,
        color:ok?T.green:T.txt2,
        fontSize:"12px",cursor:"pointer",fontFamily:"inherit",
        fontWeight:ok?700:500,
        transition:"all 0.2s",
        display:"flex",alignItems:"center",gap:"6px",
      }}>
      {ok ? "✓ Copiat!" : "📋 "+label}
    </button>
  );
}

function MCard({T,accent,label,right,children,mb="14px"}) {
  const a=accent||T.acc;
  return (
    <div style={{
      background:T.card,
      border:`1px solid ${T.bord}`,
      borderLeft:`3px solid ${a}`,
      borderRadius:"18px",overflow:"hidden",marginBottom:mb,
      boxShadow:`0 4px 24px ${T.shadow}`,
    }}>
      {label&&(
        <div style={{
          padding:"12px 18px",borderBottom:`1px solid ${T.bord}`,
          display:"flex",justifyContent:"space-between",alignItems:"center",
          background:`linear-gradient(135deg,${a}10,${a}04)`,
        }}>
          <Lbl color={a}>{label}</Lbl>
          {right}
        </div>
      )}
      <div style={{padding:"18px"}}>{children}</div>
    </div>
  );
}

function PBtn({onClick,disabled,children,T,full,sm}) {
  return (
    <button onClick={onClick} disabled={disabled} style={{
      padding:sm?"13px 22px":"18px 24px",
      borderRadius:"16px",border:"none",
      background:disabled
        ? T.faint
        : `linear-gradient(135deg,${T.acc},${T.acc2})`,
      color:disabled?T.muted:"#fff",
      fontSize:sm?"14px":"16px",fontWeight:800,
      cursor:disabled?"not-allowed":"pointer",
      fontFamily:"inherit",
      width:full?"100%":"auto",
      boxShadow:disabled?"none":`0 6px 28px ${T.acc}50, 0 2px 8px ${T.acc}30`,
      opacity:disabled?0.45:1,
      minHeight:sm?"48px":"60px",
      letterSpacing:"0.2px",
      transition:"opacity 0.2s, transform 0.1s",
    }}>{children}</button>
  );
}

function GBtn({onClick,children,T,sm}) {
  return (
    <button onClick={onClick} style={{
      padding:sm?"10px 18px":"13px 20px",
      borderRadius:"12px",
      border:`1.5px solid ${T.bord}`,
      background:T.faint,
      color:T.txt2,
      fontSize:sm?"13px":"14px",
      fontWeight:600,
      cursor:"pointer",fontFamily:"inherit",
      minHeight:sm?"44px":"50px",
      transition:"background 0.15s",
    }}>{children}</button>
  );
}

function MInput({value,onChange,placeholder,T,big,autoFocus}) {
  return (
    <input value={value} onChange={onChange} placeholder={placeholder} autoFocus={autoFocus}
      style={{
        width:"100%", padding:"16px 18px",
        background:T.faint,
        border:`2px solid ${value ? T.acc : T.bord}`,
        borderRadius:"14px",
        color:T.txt,
        fontSize:big?"17px":"15px",
        fontWeight:big?600:400,
        fontFamily:"inherit", outline:"none",
        minHeight:"58px",
        transition:"border-color 0.2s",
        boxShadow: value ? `0 0 0 3px ${T.acc}15` : "none",
      }}/>
  );
}

function MTextarea({value,onChange,placeholder,rows=3,T}) {
  return (
    <textarea value={value} onChange={onChange} placeholder={placeholder} rows={rows}
      style={{
        width:"100%", padding:"16px 18px",
        background:T.faint,
        border:`2px solid ${value ? T.acc : T.bord}`,
        borderRadius:"14px",
        color:T.txt, fontSize:"15px",
        fontFamily:"inherit", outline:"none", resize:"vertical",
        transition:"border-color 0.2s",
        lineHeight:1.6,
        boxShadow: value ? `0 0 0 3px ${T.acc}15` : "none",
      }}/>
  );
}

function BizSearch({value,onChange,T}) {
  const [q,setQ]=useState(value||"");
  const [open,setOpen]=useState(false);
  const hits=useMemo(()=>{
    const lq=q.toLowerCase().trim();
    if(!lq) return ALL_BIZ.slice(0,20);
    return ALL_BIZ.filter(b=>b.toLowerCase().includes(lq)).slice(0,20);
  },[q]);
  function pick(b){setQ(b);onChange(b);setOpen(false);}
  return (
    <div style={{position:"relative"}}>
      <div style={{position:"relative"}}>
        <span style={{position:"absolute",left:"16px",top:"50%",transform:"translateY(-50%)",fontSize:"18px",pointerEvents:"none",opacity:0.6}}>🔍</span>
        <input value={q} onChange={e=>{setQ(e.target.value);onChange("");setOpen(true);}} onFocus={()=>setOpen(true)}
          placeholder="Caută tipul afacerii tale..."
          style={{
            width:"100%", padding:"16px 16px 16px 50px",
            background:T.faint,
            border:`2px solid ${value ? T.acc : T.bord}`,
            borderRadius:"14px",
            color:T.txt, fontSize:"15px",
            fontFamily:"inherit", outline:"none",
            boxSizing:"border-box", minHeight:"58px",
            boxShadow: value ? `0 0 0 3px ${T.acc}15` : "none",
            transition:"border-color 0.2s, box-shadow 0.2s",
          }}/>
      </div>
      {open&&hits.length>0&&(
        <div style={{
          position:"absolute", zIndex:9999,
          top:"calc(100% + 8px)", left:0, right:0,
          background:T.card,
          border:`2px solid ${T.bord}`,
          borderRadius:"16px",
          maxHeight:"260px", overflowY:"auto",
          boxShadow:`0 24px 64px ${T.shadow}`,
        }}>
          {hits.map(b=>(
            <div key={b} onMouseDown={()=>pick(b)}
              style={{
                padding:"16px 18px", fontSize:"15px", cursor:"pointer",
                color:value===b ? T.acc : T.txt,
                background:value===b ? `${T.acc}12` : "transparent",
                borderBottom:`1px solid ${T.bord}`,
                fontWeight:value===b ? 700 : 400,
                minHeight:"56px", display:"flex", alignItems:"center", gap:"10px",
              }}
              onMouseEnter={e=>e.currentTarget.style.background=`${T.acc}0a`}
              onMouseLeave={e=>e.currentTarget.style.background=value===b?`${T.acc}12`:"transparent"}>
              {value===b && <span style={{color:T.acc,fontSize:"16px"}}>✓</span>}
              {b}
            </div>
          ))}
        </div>
      )}
      {open&&<div onClick={()=>setOpen(false)} style={{position:"fixed",inset:0,zIndex:9998}}/>}
    </div>
  );
}

function CitySearch({value,onChange,T}) {
  const [q,setQ]=useState(value||"");
  const [open,setOpen]=useState(false);
  const hits=useMemo(()=>{
    const lq=q.toLowerCase().trim();
    if(!lq) return ALL_CITIES.slice(0,20);
    return ALL_CITIES.filter(c=>c.toLowerCase().includes(lq)).slice(0,20);
  },[q]);
  function pick(c){setQ(c);onChange(c);setOpen(false);}
  return (
    <div style={{position:"relative"}}>
      <input value={q} onChange={e=>{setQ(e.target.value);onChange(e.target.value);setOpen(true);}} onFocus={()=>setOpen(true)}
        placeholder="Scrie orașul sau zona..."
        style={{width:"100%",padding:"14px 16px",background:T.faint,
          border:`1.5px solid ${value?T.teal:T.bord}`,borderRadius:"12px",
          color:T.txt,fontSize:"14px",fontFamily:"inherit",outline:"none",boxSizing:"border-box",minHeight:"52px"}}/>
      {open&&hits.length>0&&(
        <div style={{position:"absolute",zIndex:9999,top:"calc(100% + 6px)",left:0,right:0,
          background:T.card,border:`1px solid ${T.bord}`,borderRadius:"14px",
          maxHeight:"220px",overflowY:"auto",boxShadow:`0 20px 60px ${T.shadow}`}}>
          {hits.map(c=>(
            <div key={c} onMouseDown={()=>pick(c)}
              style={{padding:"14px 16px",fontSize:"14px",cursor:"pointer",
                color:value===c?T.teal:T.txt2,background:value===c?`${T.teal}12`:"transparent",
                borderBottom:`1px solid ${T.bord}`,fontWeight:value===c?600:400,
                minHeight:"52px",display:"flex",alignItems:"center"}}
              onMouseEnter={e=>e.currentTarget.style.background=`${T.teal}0d`}
              onMouseLeave={e=>e.currentTarget.style.background=value===c?`${T.teal}12`:"transparent"}>
              {value===c&&"✓ "}{c}
            </div>
          ))}
        </div>
      )}
      {open&&<div onClick={()=>setOpen(false)} style={{position:"fixed",inset:0,zIndex:9998}}/>}
    </div>
  );
}

// ─── VIRAL SCORE ──────────────────────────────────────────────────────────────
function ViralScore({score,T}) {
  if(!score) return null;
  const items=[
    {label:"Hook",value:score.hook,color:T.acc},
    {label:"Retentie",value:score.retention,color:T.teal},
    {label:"CTA",value:score.cta,color:T.pink},
    {label:"Emotie",value:score.emotion,color:T.gold},
  ];
  const total=Math.round((score.hook+score.retention+score.cta+score.emotion)/4*10)/10;
  const c=total>=8?T.green:total>=6?T.gold:T.red;
  return (
    <div style={{
      background:T.card,border:`1px solid ${T.bord}`,
      borderRadius:"20px",padding:"18px",marginBottom:"14px",
      boxShadow:`0 4px 24px ${T.shadow}`,
    }}>
      <div style={{display:"flex",alignItems:"center",gap:"18px",marginBottom:"16px"}}>
        <div style={{
          width:"68px",height:"68px",borderRadius:"18px",flexShrink:0,
          background:`linear-gradient(135deg,${c}22,${c}08)`,
          border:`2px solid ${c}40`,
          display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",
          boxShadow:`0 4px 16px ${c}25`,
        }}>
          <div style={{fontSize:"32px",fontWeight:800,color:c,lineHeight:1}}>{total}</div>
          <div style={{fontSize:"9px",color:T.muted,marginTop:"1px"}}>/10</div>
        </div>
        <div>
          <div style={{fontSize:"15px",fontWeight:700,color:T.txt,marginBottom:"3px"}}>Scor Viral</div>
          <div style={{fontSize:"13px",color:T.muted,lineHeight:1.4}}>
            {total>=8?"Excelent — gata de postat 🚀":total>=6?"Bun — cateva imbunatatiri ✨":"Necesita imbunatatiri ⚠️"}
          </div>
        </div>
      </div>
      <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"8px"}}>
        {items.map((it,i)=>(
          <div key={i} style={{background:T.faint,borderRadius:"12px",padding:"10px 12px"}}>
            <div style={{display:"flex",justifyContent:"space-between",marginBottom:"6px"}}>
              <span style={{fontSize:"11px",color:T.txt2,fontWeight:500}}>{it.label}</span>
              <span style={{fontSize:"12px",fontWeight:800,color:it.color}}>{it.value}/10</span>
            </div>
            <div style={{height:"4px",background:T.bord,borderRadius:"2px",overflow:"hidden"}}>
              <div style={{height:"100%",width:`${it.value*10}%`,background:it.color,borderRadius:"2px",boxShadow:`0 0 6px ${it.color}50`}}/>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ─── TIKTOK PREVIEW ───────────────────────────────────────────────────────────
function TikTokPreview({hook,overlay1,overlay2,caption,bizName,T}) {
  const [show,setShow]=useState(false);
  if(!hook) return null;
  return (
    <div style={{marginBottom:"12px"}}>
      <button onClick={()=>setShow(s=>!s)} style={{
        width:"100%",padding:"12px 16px",borderRadius:"12px",
        border:`1px solid ${T.teal}40`,background:`${T.teal}12`,
        color:T.teal,fontSize:"13px",fontWeight:600,cursor:"pointer",
        fontFamily:"inherit",marginBottom:show?"12px":"0",minHeight:"56px"}}>
        {show?"▲ Ascunde preview":"📱 Preview TikTok / Reels"}
      </button>
      {show&&(
        <div style={{display:"flex",justifyContent:"center"}}>
          <div style={{width:"200px",height:"360px",borderRadius:"20px",background:"#000",
            position:"relative",overflow:"hidden",border:"3px solid #333",
            boxShadow:"0 20px 60px rgba(0,0,0,0.7)"}}>
            <div style={{position:"absolute",inset:0,background:"linear-gradient(180deg,#1a0a2e 0%,#0d0d1a 50%,#1a0a0a 100%)"}}/>
            <div style={{position:"absolute",top:"12px",left:"12px",right:"12px",display:"flex",justifyContent:"space-between",zIndex:10}}>
              <span style={{color:"#fff",fontSize:"9px",fontWeight:700}}>@{bizName?.toLowerCase().replace(/\s/g,"_")||"afacerea_ta"}</span>
              <div style={{display:"flex",gap:"4px",alignItems:"center"}}>
                <div style={{width:"5px",height:"5px",borderRadius:"50%",background:"#ff4040"}}/>
                <span style={{color:"#fff",fontSize:"8px"}}>LIVE</span>
              </div>
            </div>
            <div style={{position:"absolute",top:"50%",left:"10px",right:"44px",transform:"translateY(-60%)",zIndex:10}}>
              <div style={{background:"rgba(0,0,0,0.75)",borderRadius:"8px",padding:"8px 10px",marginBottom:"6px"}}>
                <p style={{color:"#fff",fontSize:"10px",fontWeight:800,lineHeight:1.3,margin:0}}>"{hook}"</p>
              </div>
              {overlay1&&<div style={{background:`linear-gradient(135deg,${T.acc},${T.pink})`,borderRadius:"6px",padding:"4px 8px",marginBottom:"5px",display:"inline-block"}}><p style={{color:"#fff",fontSize:"9px",fontWeight:700,margin:0}}>{overlay1}</p></div>}
              {overlay2&&<div style={{background:"rgba(255,255,255,0.15)",borderRadius:"6px",padding:"4px 8px",display:"inline-block"}}><p style={{color:"#fff",fontSize:"9px",fontWeight:700,margin:0}}>{overlay2}</p></div>}
            </div>
            <div style={{position:"absolute",right:"8px",bottom:"70px",display:"flex",flexDirection:"column",gap:"14px",alignItems:"center",zIndex:10}}>
              {["❤️","💬","↪️","⋯"].map((ic,i)=>(
                <div key={i} style={{textAlign:"center"}}>
                  <div style={{fontSize:"18px"}}>{ic}</div>
                  <div style={{fontSize:"8px",color:"#fff",marginTop:"1px"}}>{["24K","312","1.2K",""][i]}</div>
                </div>
              ))}
            </div>
            <div style={{position:"absolute",bottom:"32px",left:0,right:0,padding:"8px 10px",background:"linear-gradient(0deg,rgba(0,0,0,0.85),transparent)",zIndex:10}}>
              <p style={{color:"#fff",fontSize:"8px",lineHeight:1.4,margin:0}}>{caption?caption.slice(0,70)+"...":"#viral #trending #fypシ"}</p>
            </div>
            <div style={{position:"absolute",bottom:0,left:0,right:0,height:"32px",background:"rgba(0,0,0,0.7)",display:"flex",alignItems:"center",justifyContent:"space-around",zIndex:11,borderTop:"1px solid rgba(255,255,255,0.1)"}}>
              {["🏠","🔍","➕","💬","👤"].map((ic,i)=>(
                <span key={i} style={{fontSize:i===2?"20px":"14px",opacity:i===2?1:0.6}}>{ic}</span>
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// ═════════════════════════════════════════════════════════════════════════════
// ROOT APP
// ═════════════════════════════════════════════════════════════════════════════
export default function App() {
  const [tab,setTab]         = useState("gen");
  const [prevTab,setPrevTab] = useState("gen");
  const [menuOpen,setMenuOpen] = useState(false);
  const [dark,setDark]       = useState(()=>LS.get("vc_dark",true));
  const [accent,setAccent]   = useState(()=>LS.get("vc_accent","violet"));
  const [history,setHistory] = useState(()=>LS.get("vc_hist",[]));
  const [favs,setFavs]       = useState(()=>LS.get("vc_favs",[]));
  const [brand,setBrand]     = useState(()=>LS.get("vc_brand",{
    bizName:"", bizType:"", platform:"", tone:"", city:"", about:"",
  }));
  const [onboarded,setOnboarded]       = useState(()=>LS.get("vc_onboarded",false));
  const [tutorialDone,setTutorialDone] = useState(()=>LS.get("vc_tutorial",false));
  const [stats,setStats]               = useState(()=>LS.get("vc_stats",{}));
  const [greeting,setGreeting]         = useState("");

  const T = buildTheme(dark, accent);

  const [bottomTabs,setBottomTabs] = useState(()=>LS.get("vc_btabs",["gen","trend","story","hist","profil"]));

  useEffect(()=>LS.set("vc_btabs",bottomTabs),[bottomTabs]);
  useEffect(()=>LS.set("vc_accent",accent),[accent]);
  useEffect(()=>LS.set("vc_hist",history.slice(0,50)),[history]);
  useEffect(()=>LS.set("vc_favs",favs),[favs]);
  useEffect(()=>LS.set("vc_brand",brand),[brand]);
  useEffect(()=>LS.set("vc_stats",stats),[stats]);
  useEffect(()=>LS.set("vc_tutorial",tutorialDone),[tutorialDone]);
  useEffect(()=>{ initPostHog(); },[]);

  // Salut personalizat la revenire
  useEffect(()=>{
    if(!onboarded) return;
    const h = new Date().getHours();
    const moment = h<12?"Bună dimineața":h<18?"Bună ziua":"Bună seara";
    const name = brand?.bizName ? " — "+brand.bizName : "";
    setGreeting(moment+name+"! 👋");
    const timer = setTimeout(()=>setGreeting(""),4000);
    return ()=>clearTimeout(timer);
  },[onboarded]);

  function haptic() { try { navigator.vibrate?.(40); } catch {} }
  function switchTab(id) {
    setPrevTab(tab); setTab(id); haptic();
    setStats(s=>({...s,[id]:(s[id]||0)+1}));
    phCapture("tab_viewed", { tab: id });
  }
  function saveItem(item) {
    setHistory(h=>[item,...h].slice(0,50));
    phCapture("content_generated", { type: item.type, platform: item.platform||"", bizType: item.bizType||"" });
  }
  function delItem(id)    { setHistory(h=>h.filter(x=>x.id!==id)); }
  function toggleFav(id)  {
    const adding = !favs.includes(id);
    setFavs(f=>adding?[...f,id]:f.filter(x=>x!==id));
    haptic();
    if(adding) phCapture("item_favorited");
  }
  function addNotif(n)    { /* dezactivat */ }
  function updateBrand(key,val) { setBrand(b=>({...b,[key]:val})); }
  function finishOnboarding() {
    setOnboarded(true);
    LS.set("vc_onboarded",true);
    phCapture("onboarding_completed");
  }

  // Show tutorial first time
  if (!tutorialDone) return <TutorialOverlay T={T} onDone={()=>setTutorialDone(true)}/>;

  return (
    <div style={{minHeight:"100vh",background:T.bg,color:T.txt,fontFamily:"'Inter',-apple-system,sans-serif",
      maxWidth:"480px",margin:"0 auto",position:"relative",overflowX:"hidden"}}>
      <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=Space+Mono&display=swap" rel="stylesheet"/>

      {/* Greeting banner */}
      {greeting&&(
        <div style={{
          position:"fixed",top:"68px",left:"50%",transform:"translateX(-50%)",
          width:"calc(100% - 32px)",maxWidth:"448px",zIndex:300,
          background:T.card,border:`1px solid ${T.bord}`,borderRadius:"14px",
          padding:"12px 18px",display:"flex",alignItems:"center",gap:"10px",
          boxShadow:`0 8px 32px ${T.shadow}`,animation:"vcSlideDown 0.4s ease",
        }}>
          <span style={{fontSize:"22px"}}>👋</span>
          <span style={{fontSize:"14px",fontWeight:600,color:T.txt}}>{greeting}</span>
        </div>
      )}

      {/* Ambient glow background */}
      <div style={{position:"fixed",top:"-100px",left:"50%",transform:"translateX(-50%)",
        width:"600px",height:"400px",
        background:`radial-gradient(ellipse,${T.acc}18 0%,transparent 70%)`,
        pointerEvents:"none",zIndex:0}}/>

      {/* TOP BAR */}
      <div style={{
        position:"sticky",top:0,zIndex:100,
        background:T.top,
        borderBottom:`1px solid ${T.bord}`,
        padding:"0 16px",
        height:"58px",
        display:"flex",justifyContent:"space-between",alignItems:"center",
        backdropFilter:"blur(20px)",
        WebkitBackdropFilter:"blur(20px)",
        boxShadow:`0 1px 0 ${T.bord}`,
      }}>
        <div style={{display:"flex",alignItems:"center",gap:"10px"}}>
          <div style={{
            width:"32px",height:"32px",borderRadius:"9px",
            overflow:"hidden",padding:0,flexShrink:0,
          }}>
            <svg width="32" height="32" viewBox="0 0 38 38" xmlns="http://www.w3.org/2000/svg">
              <defs>
                <linearGradient id="lg1" x1="0%" y1="0%" x2="100%" y2="100%">
                  <stop offset="0%" stopColor="#7c6df0"/>
                  <stop offset="100%" stopColor="#f472b6"/>
                </linearGradient>
              </defs>
              <rect width="38" height="38" rx="10" fill="#0f0d1e"/>
              <rect x="7" y="26" width="5" height="8" rx="1.5" fill="url(#lg1)" opacity="0.5"/>
              <rect x="15" y="19" width="5" height="15" rx="1.5" fill="url(#lg1)" opacity="0.75"/>
              <rect x="23" y="12" width="5" height="22" rx="1.5" fill="url(#lg1)"/>
              <circle cx="31" cy="8" r="2" fill="#f472b6" opacity="0.9"/>
            </svg>
          </div>
          <span style={{fontSize:"17px",fontWeight:800,letterSpacing:"-0.5px",
            background:`linear-gradient(135deg,${T.acc},${T.pink})`,
            WebkitBackgroundClip:"text",WebkitTextFillColor:"transparent",
            color:T.acc}}>creavo</span>
        </div>
        <div style={{display:"flex",gap:"8px",alignItems:"center"}}>
          <button onClick={()=>setDark(d=>!d)} style={{
            width:"34px",height:"34px",borderRadius:"10px",
            border:`1px solid ${T.bord}`,background:T.faint,
            cursor:"pointer",fontSize:"15px",
            display:"flex",alignItems:"center",justifyContent:"center",
          }}>{dark?"☀️":"🌙"}</button>
          <button onClick={()=>setMenuOpen(m=>!m)} style={{
            height:"36px",padding:"0 14px",borderRadius:"10px",
            border:`1.5px solid ${T.acc}`,
            background:menuOpen?`${T.acc}25`:`${T.acc}15`,
            cursor:"pointer",fontSize:"13px",fontWeight:700,
            display:"flex",alignItems:"center",justifyContent:"center",gap:"6px",
            color:T.acc,
            boxShadow:`0 2px 12px ${T.acc}35`,
            transition:"all 0.2s",
            fontFamily:"inherit",
          }}>
            <span style={{fontSize:"16px"}}>☰</span>
            <span>Meniu</span>
          </button>
        </div>
      </div>

      {/* SLIDE-IN MENU */}
      {menuOpen&&(
        <>
          <div onClick={()=>setMenuOpen(false)} style={{
            position:"fixed",inset:0,zIndex:150,
            background:"rgba(0,0,0,0.45)",
            backdropFilter:"blur(3px)",
          }}/>
          <div style={{
            position:"fixed",top:0,right:0,bottom:0,
            width:"260px",zIndex:200,
            background:T.card,
            borderLeft:`1px solid ${T.bord}`,
            boxShadow:`-8px 0 40px ${T.shadow}`,
            display:"flex",flexDirection:"column",
            animation:"vcSlideIn 0.22s ease",
            overflowY:"auto",
          }}>
            {/* Menu header */}
            <div style={{
              padding:"20px 20px 16px",
              borderBottom:`1px solid ${T.bord}`,
              display:"flex",alignItems:"center",justifyContent:"space-between",
            }}>
              <div>
                <div style={{fontSize:"15px",fontWeight:800,color:T.txt}}>Meniu</div>
                <div style={{fontSize:"13px",color:T.muted,marginTop:"2px"}}>Toate funcțiile</div>
              </div>
              <button onClick={()=>setMenuOpen(false)} style={{
                width:"32px",height:"32px",borderRadius:"8px",
                border:`1px solid ${T.bord}`,background:T.faint,
                cursor:"pointer",fontSize:"16px",color:T.muted,
                display:"flex",alignItems:"center",justifyContent:"center",
              }}>✕</button>
            </div>

            {/* Menu items */}
            <div style={{padding:"12px",flex:1}}>
              {[
                {group:"Principal",items:NAV.slice(0,5)},
                {group:"Analiză",items:NAV.slice(5,7)},
                {group:"Planificare",items:NAV.slice(7,9)},
                {group:"Cont",items:NAV.slice(9)},
              ].map((section,si)=>(
                <div key={si} style={{marginBottom:"16px"}}>
                  <div style={{
                    fontSize:"9px",fontWeight:700,letterSpacing:"2px",
                    color:T.muted,textTransform:"uppercase",
                    padding:"0 8px",marginBottom:"4px",
                  }}>{section.group}</div>
                  {section.items.map(n=>{
                    const active=tab===n.id;
                    return (
                      <button key={n.id} onClick={()=>{switchTab(n.id);setMenuOpen(false);}} style={{
                        width:"100%",display:"flex",alignItems:"center",gap:"12px",
                        padding:"11px 12px",borderRadius:"12px",border:"none",
                        background:active?`${T.acc}12`:"transparent",
                        color:active?T.acc:T.txt2,
                        fontSize:"14px",fontWeight:active?700:500,
                        cursor:"pointer",fontFamily:"inherit",
                        marginBottom:"2px",textAlign:"left",
                        transition:"all 0.15s",
                      }}>
                        <span style={{
                          width:"36px",height:"36px",borderRadius:"10px",
                          background:active?`${T.acc}18`:T.faint,
                          border:`1px solid ${active?T.acc+"35":T.bord}`,
                          display:"flex",alignItems:"center",justifyContent:"center",
                          fontSize:"18px",flexShrink:0,
                        }}>{n.icon}</span>
                        <span style={{flex:1}}>{n.label}</span>
                        {active&&<div style={{
                          width:"6px",height:"6px",borderRadius:"50%",
                          background:T.acc,flexShrink:0,
                        }}/>}
                      </button>
                    );
                  })}
                </div>
              ))}
            </div>

            {/* Version */}
            <div style={{padding:"16px 20px",borderTop:`1px solid ${T.bord}`,textAlign:"center"}}>
              <span style={{fontSize:"13px",color:T.muted}}>creavo Beta · AI Content</span>
            </div>
          </div>
        </>
      )}

      {/* CONTENT */}
      <div style={{padding:"16px 16px 90px",minHeight:"calc(100vh - 58px)",position:"relative",zIndex:1}}>
        <div key={tab} style={{animation:"vcfadein 0.22s ease"}}>
          <div style={{display:tab==="gen"     ?"block":"none"}}><GenTab    T={T} onSave={saveItem} brand={brand}/></div>
          <div style={{display:tab==="hook"    ?"block":"none"}}><HookTab   T={T} brand={brand}/></div>
          <div style={{display:tab==="video"   ?"block":"none"}}><VideoTab  T={T} brand={brand}/></div>
          <div style={{display:tab==="trend"   ?"block":"none"}}><TrendTab  T={T} onNotify={addNotif} brand={brand}/></div>
          <div style={{display:tab==="cal"     ?"block":"none"}}><CalTab    T={T} onSave={saveItem} brand={brand}/></div>
          <div style={{display:tab==="hist"    ?"block":"none"}}><HistTab   T={T} history={history} onDelete={delItem} favs={favs} toggleFav={toggleFav}/></div>
          <div style={{display:tab==="story"   ?"block":"none"}}><StoryTab  T={T} onSave={saveItem} brand={brand}/></div>
          <div style={{display:tab==="cre"     ?"block":"none"}}><CreTab    T={T} onSave={saveItem} brand={brand}/></div>
          <div style={{display:tab==="feedback" ?"block":"none"}}><FeedbackTab T={T}/></div>
          <div style={{display:tab==="despre"   ?"block":"none"}}><DespreTab   T={T}/></div>
          <div style={{display:tab==="upgrade"  ?"block":"none"}}><UpgradeTab  T={T}/></div>          <div style={{display:tab==="help"    ?"block":"none"}}><HelpTab   T={T}/></div>
          <div style={{display:tab==="profil"  ?"block":"none"}}><ProfilTab T={T} brand={brand} updateBrand={updateBrand} dark={dark} setDark={setDark} accent={accent} setAccent={setAccent} history={history} setHistory={setHistory} totalScripts={history.length} stats={stats} bottomTabs={bottomTabs} setBottomTabs={setBottomTabs}/></div>
        </div>

        {/* Footer suport pe fiecare tab */}
        {tab !== "profil" && tab !== "help" && tab !== "despre" && tab !== "feedback" && (
          <div style={{marginTop:"24px",textAlign:"center"}}>
            <button onClick={()=>window.open("https://wa.me/40720948636","_blank")} style={{
              background:"transparent",border:"none",padding:0,
              color:T.muted,fontSize:"11px",cursor:"pointer",
              fontFamily:"inherit",display:"inline-flex",alignItems:"center",gap:"5px",
            }}>
              <span>Ajutor?</span>
              <span style={{color:T.acc,fontWeight:600,textDecoration:"underline"}}>📱 0720 948 636</span>
            </button>
          </div>
        )}
      </div>
      <div style={{
        position:"fixed",bottom:0,left:"50%",transform:"translateX(-50%)",
        width:"100%",maxWidth:"480px",
        background:T.top,
        borderTop:`1px solid ${T.bord}`,
        display:"flex",
        paddingBottom:"env(safe-area-inset-bottom,8px)",
        backdropFilter:"blur(20px)",
        WebkitBackdropFilter:"blur(20px)",
        boxShadow:`0 -4px 24px ${T.shadow}`,
        zIndex:100,
      }}>
        {NAV.filter(n=>bottomTabs.includes(n.id)).map(n=>{
          const active=tab===n.id;
          return (
            <button key={n.id} onClick={()=>switchTab(n.id)} style={{
              flex:1,padding:"10px 4px 8px",
              border:"none",background:"transparent",
              color:active?T.acc:T.muted,
              cursor:"pointer",fontFamily:"inherit",
              display:"flex",flexDirection:"column",alignItems:"center",gap:"3px",
              position:"relative",transition:"color 0.2s",
            }}>
              {active&&<div style={{
                position:"absolute",top:0,left:"50%",transform:"translateX(-50%)",
                width:"24px",height:"3px",borderRadius:"0 0 3px 3px",
                background:`linear-gradient(90deg,${T.acc},${T.pink})`,
              }}/>}
              <span style={{fontSize:"24px",lineHeight:1,transform:active?"scale(1.1)":"scale(1)",transition:"transform 0.2s"}}>{n.icon}</span>
              <span style={{fontSize:"11px",fontWeight:active?700:400,lineHeight:1,whiteSpace:"nowrap"}}>{n.label}</span>
            </button>
          );
        })}
      </div>

      <style>{`
        @keyframes vcpop{from{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}
        @keyframes vcfadein{from{opacity:0;transform:translateY(5px)}to{opacity:1;transform:translateY(0)}}
        @keyframes vcSlideIn{from{opacity:0;transform:translateX(100%)}to{opacity:1;transform:translateX(0)}}
        @keyframes vcSlideDown{from{opacity:0;transform:translateX(-50%) translateY(-16px)}to{opacity:1;transform:translateX(-50%) translateY(0)}}
        *{box-sizing:border-box;}
        ::-webkit-scrollbar{width:3px;}
        ::-webkit-scrollbar-thumb{background:#33334a60;border-radius:3px;}
        input::placeholder,textarea::placeholder{color:#55556a;}
        button:active{transform:scale(0.96);}
        input,textarea,select{-webkit-appearance:none;}
      `}</style>
    </div>
  );
}
// ═════════════════════════════════════════════════════════════════════════════
// GENERATOR
// ═════════════════════════════════════════════════════════════════════════════
function GenTab({T,onSave,brand}) {
  const [bizName,setBizName]   = useState(brand?.bizName||"");
  const [bizType,setBizType]   = useState(brand?.bizType||"");
  const [tone,setTone]         = useState(brand?.tone||"");
  const [platform,setPlatform] = useState(brand?.platform||"");
  const [duration,setDuration] = useState("");
  const [template,setTemplate] = useState("generic");
  const [extra,setExtra]       = useState("");
  const [limba,setLimba]       = useState("romana");
  const [loading,setLoading]   = useState(false);
  const [result,setResult]     = useState(null);
  const [err,setErr]           = useState("");
  const [copied,setCopied]     = useState(false);
  const [regen,setRegen]       = useState({});
  const [showSuccess,setShowSuccess] = useState(false);
  const [showMoreTemplates,setShowMoreTemplates] = useState(false);

  // ─── Limită zilnică 5 generări / 12 ore ───────────────────────────────────
  const LIMIT = 5;
  const INTERVAL_MS = 12 * 60 * 60 * 1000; // 12 ore

  function getLimitData() {
    try {
      const d = JSON.parse(localStorage.getItem("vc_gen_limit")||"{}");
      const now = Date.now();
      if (!d.resetAt || now >= d.resetAt) {
        return { count:0, resetAt: now + INTERVAL_MS };
      }
      return d;
    } catch { return { count:0, resetAt: Date.now() + INTERVAL_MS }; }
  }

  const [limitData, setLimitData] = useState(getLimitData);
  const remaining = Math.max(0, LIMIT - limitData.count);

  function msToReset() {
    const ms = Math.max(0, limitData.resetAt - Date.now());
    const h = Math.floor(ms / 3600000);
    const m = Math.floor((ms % 3600000) / 60000);
    return h > 0 ? `${h}h ${m}min` : `${m} minute`;
  }

  function incrementLimit() {
    const d = getLimitData();
    const updated = { ...d, count: d.count + 1 };
    localStorage.setItem("vc_gen_limit", JSON.stringify(updated));
    setLimitData(updated);
  }

  const isMix=duration.includes("-");
  const canGen=bizName.trim()&&bizType&&tone&&platform&&duration&&remaining>0;
  const tmpl=TEMPLATES.find(t=>t.id===template);

  function buildPrompt(section) {
    const dc=getDateContext();
    const tDesc={
      generic:"Script complet personalizat",
      poveste:"Inainte→Problema→Descoperire→Transformare",
      pov:"POV: [situatie]. Vizitatorul traieste direct.",
      "3greseli":"3 greseli comune + solutia ta",
      inainte:"Inainte/Dupa. Contrast puternic.",
      mit:"MIT: [fals] — REALITATEA: [adevarul tau]",
      reactie:"Reactie autentica client real.",
      trend:"Trend viral "+dc.complet+" adaptat.",
    }[template]||"";
    const aboutCtx = brand?.about ? " Despre afacere: "+brand.about+"." : "";
    const limbaCtx = limba==="engleza" ? " Scrie scriptul in engleza." : " Scrie scriptul in romana.";
    return (
      "Copywriter viral Romania, "+dc.complet+". "+
      (section?"Regenerează DOAR: "+section+". ":"")+
      "Template: "+tDesc+". "+
      "Afacere: "+bizName+", "+bizType+", "+platform+", "+duration+", ton "+tone+
      (extra?", "+extra:"")+"."+aboutCtx+limbaCtx+"\n"+
      "Reguli: numele exact '"+bizName+"', hook unic, script natural."+
      (isMix?" Marcheaza [OPT:] partile optionale.":"")+"\n"+
      "Raspunde DOAR cu JSON:\n"+
      "{\"hook\":\"hook "+bizName+"\",\"hook_b\":\"hook B\",\"hook_why\":\"motiv scurt\","+
      "\"sec_hook\":\"0-3sec\",\"sec_atentie\":\"3-8sec\",\"sec_solutie\":\"solutie\","+
      "\"sec_dovada\":\"dovada\",\"sec_cta\":\"cta\",\"script\":\"script complet\","+
      "\"overlay1\":\"txt1\",\"overlay2\":\"txt2\",\"overlay3\":\"txt3\","+
      "\"caption\":\"caption+hashtag "+platform+" "+dc.an+"\","+
      "\"filmare\":\"3 sfaturi scurte\","+
      "\"score_hook\":8,\"score_retention\":7,\"score_cta\":8,\"score_emotion\":7}"
    );
  }

  async function generate() {
    if (remaining <= 0) return;
    setLoading(true);setErr("");setResult(null);
    try {
      const r=await callAI(buildPrompt());
      if(!r.hook||!r.script) throw new Error("Raspuns incomplet. Încearcă din nou.");
      setResult(r);
      incrementLimit();
      setShowSuccess(true);
      setTimeout(()=>setShowSuccess(false),3000);
      phCapture("script_generated", { bizType, platform, duration, template, limba });
      onSave({id:Date.now(),type:"script",bizName,bizType,platform,duration,tone,template,
        hook:r.hook,hook_b:r.hook_b||"",script:r.script,caption:r.caption||"",
        date:new Date().toLocaleDateString("ro-RO")});
    } catch(e){setErr(e.message||"Eroare. Încearcă din nou.");}
    finally{setLoading(false);}
  }

  async function regenSection(key) {
    setRegen(r=>({...r,[key]:true}));
    try {
      const r=await callAI(buildPrompt(key));
      setResult(prev=>({...prev,...r}));
    } catch(e){setErr(e.message);}
    finally{setRegen(r=>({...r,[key]:false}));}
  }

  function copyAll() {
    if(!result) return;
    navigator.clipboard.writeText(
      bizName+" — "+platform+" — "+duration+"\nTemplate: "+tmpl?.label+
      "\n\nHOOK A: \""+result.hook+"\""+
      "\nHOOK B: \""+(result.hook_b||"")+"\""+
      "\n\nSCRIPT:\n"+result.script+
      "\n\nCAPTION:\n"+(result.caption||"")+
      "\n\n— Generat cu Creavo AI"
    );
    setCopied(true);setTimeout(()=>setCopied(false),2500);
  }

  if(loading) return <Dots label={"Scriu scriptul pentru "+bizName+"..."} T={T}/>;

  if(result) {
    const score=result.score_hook?{hook:result.score_hook,retention:result.score_retention,cta:result.score_cta,emotion:result.score_emotion}:null;
    return (
      <div style={{animation:"vcpop 0.3s ease"}}>
        <div style={{display:"flex",justifyContent:"space-between",alignItems:"flex-start",marginBottom:"16px"}}>
          <div>
            <h2 style={{margin:0,fontSize:"20px",fontWeight:800}}>{bizName}</h2>
            <p style={{margin:"4px 0 0",color:T.muted,fontSize:"11px",fontFamily:"'Space Mono'"}}>{bizType} · {platform} · {duration}</p>
          </div>
          <div style={{display:"flex",gap:"8px"}}>
            <GBtn T={T} sm onClick={()=>setResult(null)}>↩</GBtn>
            <GBtn T={T} sm onClick={generate}>↻</GBtn>
          </div>
        </div>

        <TikTokPreview hook={result.hook} overlay1={result.overlay1} overlay2={result.overlay2} caption={result.caption} bizName={bizName} T={T}/>
        <ViralScore score={score} T={T}/>

        {isMix&&<div style={{padding:"10px 14px",background:`${T.gold}15`,border:`1px solid ${T.gold}40`,borderRadius:"12px",fontSize:"12px",color:T.gold,marginBottom:"12px"}}>⚡ Durata mixta — sectiunile [OPT:] pot fi taiate</div>}

        {/* HOOK */}
        <div style={{background:`linear-gradient(135deg,${T.acc}18,${T.pink}12)`,border:`1px solid ${T.acc}30`,borderRadius:"16px",padding:"18px",marginBottom:"12px"}}>
          <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"8px"}}>
            <Lbl color={T.acc}>Hook — Varianta A</Lbl>
            <button onClick={()=>regenSection("hook")} disabled={regen.hook} style={{padding:"5px 11px",borderRadius:"9px",border:`1px solid ${T.acc}40`,background:`${T.acc}12`,color:T.acc,fontSize:"11px",cursor:"pointer",fontFamily:"inherit"}}>
              {regen.hook?"...":"↻ Regenerează"}
            </button>
          </div>
          <p style={{fontSize:"clamp(19px,4vw,24px)",fontWeight:800,lineHeight:1.25,color:T.txt,margin:"0 0 10px"}}>"{result.hook}"</p>
          {result.hook_why&&<div style={{padding:"8px 12px",background:`${T.acc}12`,borderLeft:`3px solid ${T.acc}`,borderRadius:"0 8px 8px 0",fontSize:"12px",color:T.txt2,marginBottom:"10px"}}>💡 {result.hook_why}</div>}
          {result.hook_b&&(
            <div style={{padding:"12px 14px",background:`${T.pink}10`,borderLeft:`3px solid ${T.pink}`,borderRadius:"0 10px 10px 0"}}>
              <Lbl color={T.pink}>Hook B — A/B Test</Lbl>
              <p style={{margin:0,fontSize:"15px",color:T.txt,fontStyle:"italic"}}>"{result.hook_b}"</p>
            </div>
          )}
        </div>

        {/* SECTIONS */}
        <MCard T={T} accent={T.acc} label="Script pe sectiuni">
          {[
            {lbl:"Hook 0-3 sec",val:result.sec_hook,key:"sec_hook"},
            {lbl:"Atentie 3-8 sec",val:result.sec_atentie,key:"sec_atentie"},
            {lbl:"Solutie",val:result.sec_solutie,key:"sec_solutie"},
            {lbl:"Dovada",val:result.sec_dovada,key:"sec_dovada"},
            {lbl:"Call to Action",val:result.sec_cta,key:"sec_cta"},
          ].filter(s=>s.val).map((s,i,arr)=>(
            <div key={i} style={{paddingBottom:"12px",marginBottom:"12px",borderBottom:i<arr.length-1?`1px solid ${T.bord}`:"none"}}>
              <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"5px"}}>
                <Lbl color={T.muted}>{s.lbl}</Lbl>
                <button onClick={()=>regenSection(s.key)} disabled={regen[s.key]} style={{padding:"3px 9px",borderRadius:"8px",border:`1px solid ${T.bord}`,background:"transparent",color:T.muted,fontSize:"11px",cursor:"pointer",fontFamily:"inherit"}}>{regen[s.key]?"...":"↻"}</button>
              </div>
              <p style={{margin:0,fontSize:"15px",lineHeight:1.75,color:T.txt2}}>{s.val}</p>
            </div>
          ))}
        </MCard>

        <MCard T={T} accent={T.teal} label="Script Complet" right={<CBtn T={T} text={result.script}/>}>
          <pre style={{margin:0,fontFamily:"'Space Mono'",fontSize:"12px",lineHeight:1.85,color:T.txt,whiteSpace:"pre-wrap",wordBreak:"break-word"}}>{result.script}</pre>
        </MCard>

        <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"10px",marginBottom:"12px"}}>
          <MCard T={T} accent={T.gold} label="Overlay" mb="0">
            {[result.overlay1,result.overlay2,result.overlay3].filter(Boolean).map((o,i)=>(
              <div key={i} style={{padding:"8px 10px",background:`${T.gold}12`,borderLeft:`3px solid ${T.gold}`,borderRadius:"0 8px 8px 0",fontSize:"12px",color:T.txt,marginBottom:"7px"}}>{o}</div>
            ))}
          </MCard>
          <MCard T={T} accent="#06b6d4" label="Filmare" mb="0">
            <p style={{margin:0,fontSize:"12px",color:T.txt2,lineHeight:1.6}}>{result.filmare}</p>
          </MCard>
        </div>

        <MCard T={T} accent={T.pink} label="Caption + Hashtag-uri" right={<CBtn T={T} text={result.caption}/>}>
          <div style={{display:"flex",justifyContent:"space-between",alignItems:"flex-start",gap:"10px"}}>
            <p style={{margin:0,fontSize:"13px",lineHeight:1.7,color:T.txt2,flex:1}}>{result.caption}</p>
            <button onClick={()=>regenSection("caption")} disabled={regen.caption} style={{padding:"5px 10px",borderRadius:"9px",border:`1px solid ${T.pink}40`,background:`${T.pink}12`,color:T.pink,fontSize:"11px",cursor:"pointer",fontFamily:"inherit",flexShrink:0}}>{regen.caption?"...":"↻"}</button>
          </div>
        </MCard>

        {err&&<ErrBox T={T} msg={err} retry={generate}/>}

        {/* Success notification — fixed top banner */}
        {showSuccess&&(
          <div style={{
            position:"fixed",top:"70px",left:"50%",transform:"translateX(-50%)",
            width:"calc(100% - 32px)",maxWidth:"448px",
            padding:"14px 18px",borderRadius:"16px",
            background:`linear-gradient(135deg,${T.green},#16a34a)`,
            display:"flex",alignItems:"center",gap:"12px",
            animation:"vcSlideDown 0.4s ease",
            zIndex:500,
            boxShadow:`0 8px 32px rgba(74,222,128,0.5)`,
          }}>
            <span style={{fontSize:"24px"}}>🎉</span>
            <div style={{flex:1}}>
              <div style={{fontSize:"14px",fontWeight:800,color:"#fff"}}>Script generat cu succes!</div>
              <div style={{fontSize:"12px",color:"rgba(255,255,255,0.8)"}}>Salvat automat în Istoric ✓</div>
            </div>
          </div>
        )}

        {/* WhatsApp + PDF */}
        {result&&(
          <div style={{display:"flex",flexDirection:"column",gap:"8px"}}>
            <button onClick={()=>{
              phCapture("whatsapp_share", { bizType });
              const text = encodeURIComponent(
                "🎬 Script video pentru "+bizName+"\n\n"+
                "HOOK: \""+result.hook+"\"\n\n"+
                "SCRIPT:\n"+result.script+"\n\n"+
                "CAPTION:\n"+(result.caption||"")+
                "\n\n— Generat cu Creavo AI"
              );
              window.open("https://wa.me/?text="+text,"_blank");
            }} style={{
              width:"100%",padding:"14px",borderRadius:"14px",border:"none",
              background:"#25D366",color:"#fff",
              fontSize:"14px",fontWeight:700,cursor:"pointer",fontFamily:"inherit",
              minHeight:"52px",display:"flex",alignItems:"center",justifyContent:"center",gap:"8px",
              boxShadow:"0 4px 20px rgba(37,211,102,0.4)",
            }}>
              <span style={{fontSize:"18px"}}>📱</span>
              Trimite pe WhatsApp
            </button>

            <button onClick={()=>{
              const content =
                "CREAVO — Script Video\n"+("═".repeat(40))+"\n\n"+
                "Afacere: "+bizName+"\nTip: "+bizType+"\nPlatforma: "+platform+"\nDurata: "+duration+"\nTemplate: "+(tmpl?.label||"")+"\n\n"+
                ("─".repeat(40))+"\nHOOK A:\n\""+result.hook+"\"\n\n"+
                (result.hook_b ? "HOOK B:\n\""+result.hook_b+"\"\n\n" : "")+
                ("─".repeat(40))+"\nSCRIPT COMPLET:\n\n"+result.script+"\n\n"+
                ("─".repeat(40))+"\nCAPTION + HASHTAG-URI:\n\n"+(result.caption||"")+"\n\n"+
                ("─".repeat(40))+"\nSFATURI FILMARE:\n"+(result.filmare||"")+"\n\n"+
                ("═".repeat(40))+"\nGenerat cu Creavo AI\n"+new Date().toLocaleDateString("ro-RO");
              const blob = new Blob([content], {type:"text/plain;charset=utf-8"});
              const url = URL.createObjectURL(blob);
              const a = document.createElement("a");
              a.href=url; a.download="creavo-script-"+bizName.replace(/\s/g,"-").toLowerCase()+".txt";
              a.click(); URL.revokeObjectURL(url);
              phCapture("export_doc", { bizType });
            }} style={{
              width:"100%",padding:"14px",borderRadius:"14px",
              border:`1px solid ${T.bord}`,
              background:T.faint,color:T.txt2,
              fontSize:"14px",fontWeight:600,cursor:"pointer",fontFamily:"inherit",
              minHeight:"52px",display:"flex",alignItems:"center",justifyContent:"center",gap:"8px",
            }}>
              <span style={{fontSize:"18px"}}>📄</span>
              Descarcă ca document (.txt)
            </button>
          </div>
        )}
      </div>
    );
  }

  return (
    <div style={{display:"flex",flexDirection:"column",gap:"18px",animation:"vcpop 0.3s ease"}}>
      {err&&<ErrBox T={T} msg={err} retry={generate}/>}

      <div style={{background:`linear-gradient(135deg,${T.acc}12,${T.pink}08)`,border:`1px solid ${T.acc}25`,borderRadius:"16px",padding:"16px"}}>
        <Lbl color={T.acc}>Numele afacerii tale</Lbl>
        <MInput value={bizName} onChange={e=>setBizName(e.target.value)} placeholder="Numele afacerii tale" T={T} big autoFocus/>
        <p style={{margin:"8px 0 0",fontSize:"13px",color:T.muted}}>⚡ AI-ul va folosi exact acest nume</p>
      </div>

      <div>
        <Lbl color={T.muted}>Tipul afacerii</Lbl>
        <BizSearch value={bizType} onChange={setBizType} T={T}/>
        {bizType&&<div style={{marginTop:"8px",padding:"10px 14px",background:`${T.acc}12`,border:`1px solid ${T.acc}25`,borderRadius:"10px",fontSize:"14px",color:T.acc,fontWeight:600}}>✓ {bizType}</div>}
      </div>

      <div>
        <Lbl color={T.muted}>Template viral</Lbl>
        <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"8px",marginBottom:"8px"}}>
          {TEMPLATES.filter(tpl=>["generic","trend"].includes(tpl.id)).map(tpl=>(
            <button key={tpl.id} onClick={()=>setTemplate(tpl.id)} style={{
              padding:"14px",borderRadius:"12px",border:`2px solid ${template===tpl.id?T.acc:T.bord}`,
              background:template===tpl.id?`${T.acc}12`:T.faint,color:template===tpl.id?T.acc:T.txt2,
              cursor:"pointer",fontFamily:"inherit",textAlign:"left",minHeight:"80px"}}>
              <div style={{fontSize:"22px",marginBottom:"5px"}}>{tpl.icon}</div>
              <div style={{fontSize:"14px",fontWeight:template===tpl.id?800:600,color:template===tpl.id?T.acc:T.txt}}>{tpl.label}</div>
              <div style={{fontSize:"12px",color:T.muted,marginTop:"3px"}}>{tpl.desc}</div>
            </button>
          ))}
        </div>
        {/* Expand more templates */}
        {!showMoreTemplates ? (
          <button onClick={()=>setShowMoreTemplates(true)} style={{
            width:"100%",padding:"12px 16px",borderRadius:"12px",
            border:`1.5px solid ${T.bord}`,background:T.faint,
            color:T.txt2,fontSize:"14px",fontWeight:600,
            cursor:"pointer",fontFamily:"inherit",minHeight:"50px",
            display:"flex",alignItems:"center",justifyContent:"center",gap:"8px",
          }}>
            <span>📂</span> Mai multe tipuri de script ▼
          </button>
        ) : (
          <div>
            <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"8px",marginBottom:"8px"}}>
              {TEMPLATES.filter(tpl=>!["generic","trend"].includes(tpl.id)).map(tpl=>(
                <button key={tpl.id} onClick={()=>setTemplate(tpl.id)} style={{
                  padding:"14px",borderRadius:"12px",border:`2px solid ${template===tpl.id?T.acc:T.bord}`,
                  background:template===tpl.id?`${T.acc}12`:T.faint,color:template===tpl.id?T.acc:T.txt2,
                  cursor:"pointer",fontFamily:"inherit",textAlign:"left",minHeight:"80px"}}>
                  <div style={{fontSize:"22px",marginBottom:"5px"}}>{tpl.icon}</div>
                  <div style={{fontSize:"14px",fontWeight:template===tpl.id?800:600,color:template===tpl.id?T.acc:T.txt}}>{tpl.label}</div>
                  <div style={{fontSize:"12px",color:T.muted,marginTop:"3px"}}>{tpl.desc}</div>
                </button>
              ))}
            </div>
            <button onClick={()=>setShowMoreTemplates(false)} style={{
              width:"100%",padding:"10px",borderRadius:"12px",
              border:`1px solid ${T.bord}`,background:"transparent",
              color:T.muted,fontSize:"13px",cursor:"pointer",fontFamily:"inherit",
            }}>▲ Ascunde</button>
          </div>
        )}
        {template && template !== "generic" && (
          <div style={{marginTop:"8px",padding:"10px 14px",background:`${T.acc}12`,border:`1px solid ${T.acc}25`,borderRadius:"10px",fontSize:"13px",color:T.acc,fontWeight:600}}>
            ✓ Selectat: {TEMPLATES.find(t=>t.id===template)?.label}
          </div>
        )}
      </div>

      <div>
        <Lbl color={T.muted}>Tonul videoclipului</Lbl>
        <div style={{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:"8px"}}>
          {TONES.map(t=>(
            <button key={t} onClick={()=>setTone(t)} style={{
              padding:"12px 8px",borderRadius:"12px",minHeight:"56px",
              border:`1.5px solid ${tone===t?T.pink:T.bord}`,
              background:tone===t?`${T.pink}12`:T.faint,
              color:tone===t?T.pink:T.txt2,fontSize:"12px",
              fontWeight:tone===t?600:400,cursor:"pointer",fontFamily:"inherit"}}>{t}</button>
          ))}
        </div>
      </div>

      <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"14px"}}>
        <div>
          <Lbl color={T.muted}>Platforma</Lbl>
          {PLATFORMS.map(p=>(
            <button key={p} onClick={()=>setPlatform(p)} style={{
              display:"block",width:"100%",marginBottom:"8px",
              padding:"12px 14px",borderRadius:"12px",minHeight:"56px",
              border:`1.5px solid ${platform===p?T.teal:T.bord}`,
              background:platform===p?`${T.teal}12`:T.faint,
              color:platform===p?T.teal:T.txt2,fontSize:"12px",
              fontWeight:platform===p?600:400,cursor:"pointer",fontFamily:"inherit",textAlign:"left"}}>{p}</button>
          ))}
        </div>
        <div>
          <Lbl color={T.muted}>Durata</Lbl>
          {DURATIONS.map(d=>(
            <button key={d} onClick={()=>setDuration(d)} style={{
              display:"flex",justifyContent:"space-between",alignItems:"center",
              width:"100%",marginBottom:"8px",padding:"12px 14px",borderRadius:"12px",minHeight:"56px",
              border:`1.5px solid ${duration===d?T.teal:T.bord}`,
              background:duration===d?`${T.teal}12`:T.faint,
              color:duration===d?T.teal:T.txt2,fontSize:"12px",
              fontWeight:duration===d?600:400,cursor:"pointer",fontFamily:"inherit"}}>
              {d}
              {d.includes("-")&&<span style={{fontSize:"9px",padding:"2px 6px",borderRadius:"10px",background:`${T.teal}20`,color:T.teal}}>MIX</span>}
            </button>
          ))}
        </div>
      </div>

      <div>
        <Lbl color={T.muted}>Detalii extra (optional)</Lbl>
        <MTextarea value={extra} onChange={e=>setExtra(e.target.value)} placeholder="ex: promotie 30%, nou deschis, livrare gratuita..." T={T}/>
      </div>

      <div>
        <Lbl color={T.muted}>Limba scriptului</Lbl>
        <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"8px"}}>
          {[{id:"romana",label:"🇷🇴 Română"},{id:"engleza",label:"🇬🇧 Engleză"}].map(l=>(
            <button key={l.id} onClick={()=>setLimba(l.id)} style={{
              padding:"12px",borderRadius:"12px",minHeight:"56px",
              border:`1.5px solid ${limba===l.id?T.acc:T.bord}`,
              background:limba===l.id?`${T.acc}12`:T.faint,
              color:limba===l.id?T.acc:T.txt2,
              fontSize:"13px",fontWeight:limba===l.id?700:400,
              cursor:"pointer",fontFamily:"inherit",
            }}>{l.label}</button>
          ))}
        </div>
      </div>

      {/* Limită zilnică */}
      <div style={{
        background:remaining===0?`${T.red}12`:`${T.acc}08`,
        border:`1px solid ${remaining===0?T.red+"40":T.bord}`,
        borderRadius:"14px",padding:"14px 16px",
      }}>
        <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"8px"}}>
          <span style={{fontSize:"14px",fontWeight:700,color:remaining===0?T.red:T.txt}}>
            {remaining===0?"⛔ Limită atinsă":"⚡ Generări disponibile azi"}
          </span>
          <span style={{fontSize:"15px",fontWeight:800,color:remaining===0?T.red:T.acc}}>
            {remaining} / {LIMIT}
          </span>
        </div>
        <div style={{height:"6px",background:T.bord,borderRadius:"3px",overflow:"hidden",marginBottom:"8px"}}>
          <div style={{
            height:"100%",
            width:`${(remaining/LIMIT)*100}%`,
            background:remaining===0?T.red:remaining<=2?T.gold:T.acc,
            borderRadius:"3px",transition:"width 0.4s",
          }}/>
        </div>
        <p style={{margin:0,fontSize:"12px",color:T.muted}}>
          {remaining===0?`Se resetează în ${msToReset()}`:"Se resetează la fiecare 12 ore"}
        </p>
      </div>

      {remaining===0?(
        <div style={{padding:"20px",borderRadius:"14px",background:`${T.red}10`,border:`1px solid ${T.red}30`,textAlign:"center"}}>
          <div style={{fontSize:"36px",marginBottom:"10px"}}>⏰</div>
          <div style={{fontSize:"16px",fontWeight:700,color:T.red,marginBottom:"6px"}}>Ai folosit toate cele {LIMIT} generări</div>
          <div style={{fontSize:"13px",color:T.muted,lineHeight:1.5}}>Revino în {msToReset()} pentru mai multe scripturi</div>
        </div>
      ):(
        <PBtn T={T} onClick={generate} disabled={!canGen} full>
          {canGen?`⚡ Generează Script pentru "${bizName}"`:"Completează câmpurile de mai sus ↑"}
        </PBtn>
      )}
    </div>
  );
}

// ═════════════════════════════════════════════════════════════════════════════
// TRENDURI
// ═════════════════════════════════════════════════════════════════════════════
function TrendTab({T,onNotify,brand}) {
  const [bizType,setBizType]=useState(brand?.bizType||"");
  const [loading,setLoading]=useState(false);
  const [data,setData]=useState(null);
  const [err,setErr]=useState("");
  const [subs,setSubs]=useState([]);

  function toggleSub(t){setSubs(s=>s.includes(t)?s.filter(x=>x!==t):[...s,t]);if(!subs.includes(t))onNotify({emoji:"🔔",title:"Abonat: "+t,body:"Vei primi notificari."});}

  async function gen(){
    if(!bizType) return;
    setLoading(true);setErr("");setData(null);
    const dc=getDateContext();
    const p=
      "Trenduri virale Romania, "+dc.complet+", "+dc.sezon+". Afacere: "+bizType+".\n"+
      "Raspunde DOAR cu JSON:\n"+
      "{\"alert\":\"alerta "+dc.complet+" max 15 cuvinte\","+
      "\"t1\":\"trend1\",\"t1p\":\"platforma\",\"t1w\":\"de ce viral max 8 cuvinte\",\"t1h\":\"hook scurt\",\"t1u\":\"high\",\"t1d\":\"durata\","+
      "\"t2\":\"trend2\",\"t2p\":\"\",\"t2w\":\"\",\"t2h\":\"\",\"t2u\":\"high\",\"t2d\":\"\","+
      "\"t3\":\"trend3\",\"t3p\":\"\",\"t3w\":\"\",\"t3h\":\"\",\"t3u\":\"medium\",\"t3d\":\"\","+
      "\"t4\":\"trend4\",\"t4p\":\"\",\"t4w\":\"\",\"t4h\":\"\",\"t4u\":\"medium\",\"t4d\":\"\","+
      "\"t5\":\"trend5\",\"t5p\":\"\",\"t5w\":\"\",\"t5h\":\"\",\"t5u\":\"medium\",\"t5d\":\"\","+
      "\"s1\":\"sound "+dc.an+"\",\"s2\":\"sound2\",\"s3\":\"sound3\","+
      "\"h1\":\"#tag1\",\"h2\":\"#tag2\",\"h3\":\"#tag3\",\"h4\":\"#tag4\",\"h5\":\"#tag5\","+
      "\"a1\":\"evita1 max 8 cuvinte\",\"a2\":\"evita2\"}";
    try{
      const r=await callAI(p);setData(r);
      onNotify({emoji:"🔥",title:"Trenduri "+bizType,body:r.alert||"Trenduri generate!"});
    }catch(e){setErr(e.message||"Eroare. Încearcă din nou.");}
    finally{setLoading(false);}
  }

  if(loading) return <Dots label={"Analizez trenduri pentru "+bizType+"..."} T={T}/>;
  const trends=data?[1,2,3,4,5].map(i=>({name:data["t"+i],platform:data["t"+i+"p"],why:data["t"+i+"w"],hook:data["t"+i+"h"],urgent:data["t"+i+"u"],dur:data["t"+i+"d"]})).filter(t=>t.name):[];

  return (
    <div>
      <div style={{display:"flex",gap:"10px",marginBottom:"14px"}}>
        <div style={{flex:1}}><BizSearch value={bizType} onChange={setBizType} T={T}/></div>
        <PBtn T={T} sm onClick={gen} disabled={!bizType}>Analizează</PBtn>
      </div>
      {subs.length>0&&<div style={{padding:"12px 14px",background:T.faint,border:`1px solid ${T.bord}`,borderRadius:"12px",marginBottom:"12px"}}><Lbl color={T.muted}>Abonamente active</Lbl><div style={{display:"flex",gap:"6px",flexWrap:"wrap"}}>{subs.map(s=><span key={s} onClick={()=>toggleSub(s)} style={{padding:"5px 12px",borderRadius:"20px",background:`${T.acc}15`,border:`1px solid ${T.acc}30`,color:T.acc,fontSize:"12px",cursor:"pointer",minHeight:"36px",display:"flex",alignItems:"center"}}>{s} ✕</span>)}</div></div>}
      {err&&<ErrBox T={T} msg={err} retry={gen}/>}
      {data&&(
        <div style={{animation:"vcpop 0.3s ease"}}>
          <div style={{background:`${T.red}12`,border:`1px solid ${T.red}35`,borderRadius:"14px",padding:"14px 16px",marginBottom:"14px",display:"flex",gap:"12px"}}>
            <span style={{fontSize:"20px"}}>🚨</span>
            <div><Lbl color={T.red}>Alerta Trend</Lbl><p style={{margin:0,fontSize:"13px",color:T.red,lineHeight:1.5}}>{data.alert}</p></div>
          </div>
          <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"12px"}}>
            <Lbl color={T.acc}>Trending — {bizType}</Lbl>
            <button onClick={()=>toggleSub(bizType)} style={{padding:"7px 14px",borderRadius:"20px",fontSize:"12px",cursor:"pointer",fontFamily:"inherit",fontWeight:600,border:`1px solid ${subs.includes(bizType)?T.acc:T.bord}`,background:subs.includes(bizType)?`${T.acc}12`:"transparent",color:subs.includes(bizType)?T.acc:T.muted,minHeight:"36px"}}>
              {subs.includes(bizType)?"🔔 Abonat":"🔔 Aboneaza-te"}
            </button>
          </div>
          {trends.map((t,i)=>(
            <div key={i} style={{background:T.card,border:`1px solid ${T.bord}`,borderLeft:`4px solid ${t.urgent==="high"?T.red:T.gold}`,borderRadius:"14px",padding:"14px 16px",marginBottom:"10px",boxShadow:`0 2px 12px ${T.shadow}`}}>
              <div style={{display:"flex",justifyContent:"space-between",marginBottom:"8px",gap:"8px"}}>
                <div style={{display:"flex",gap:"8px",alignItems:"center",flexWrap:"wrap"}}>
                  <span style={{fontSize:"14px",fontWeight:700}}>{t.name}</span>
                  <span style={{fontSize:"11px",padding:"3px 9px",borderRadius:"20px",background:T.faint,color:T.muted}}>{t.platform}</span>
                </div>
                <span style={{fontSize:"11px",padding:"4px 10px",borderRadius:"20px",fontWeight:700,flexShrink:0,background:t.urgent==="high"?`${T.red}15`:`${T.gold}15`,color:t.urgent==="high"?T.red:T.gold}}>
                  {t.urgent==="high"?"🔥 URGENT":"⚡ ACTIV"}
                </span>
              </div>
              <p style={{margin:"0 0 10px",fontSize:"13px",color:T.txt2,lineHeight:1.5}}>{t.why}</p>
              <div style={{padding:"10px 12px",background:`${T.acc}0d`,borderLeft:`3px solid ${T.acc}`,borderRadius:"0 10px 10px 0"}}>
                <Lbl color={T.acc}>Idee Hook</Lbl>
                <p style={{margin:0,fontSize:"13px",color:T.txt,fontStyle:"italic"}}>"{t.hook}"</p>
              </div>
              <p style={{margin:"7px 0 0",fontSize:"13px",color:T.muted}}>⏱ {t.dur}</p>
            </div>
          ))}
          <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"10px",marginBottom:"10px"}}>
            <MCard T={T} accent={T.pink} label="Sounds" mb="0">{[data.s1,data.s2,data.s3].filter(Boolean).map((s,i)=><p key={i} style={{margin:0,padding:"6px 0",fontSize:"13px",color:T.txt2,borderBottom:i<2?`1px solid ${T.bord}`:"none"}}>{s}</p>)}</MCard>
            <MCard T={T} accent={T.teal} label="Hashtag-uri" mb="0"><div style={{display:"flex",flexWrap:"wrap",gap:"5px"}}>{[data.h1,data.h2,data.h3,data.h4,data.h5].filter(Boolean).map((h,i)=><span key={i} style={{padding:"4px 10px",borderRadius:"20px",background:`${T.teal}15`,color:T.teal,fontSize:"11px"}}>{h}</span>)}</div></MCard>
          </div>
          <MCard T={T} accent={T.red} label="Ce sa eviti">{[data.a1,data.a2].filter(Boolean).map((a,i)=><div key={i} style={{display:"flex",gap:"10px",marginBottom:"8px"}}><span style={{color:T.red,fontSize:"16px"}}>✗</span><span style={{fontSize:"13px",color:T.txt2,lineHeight:1.5}}>{a}</span></div>)}</MCard>
          <GBtn T={T} onClick={gen}>↻ Actualizează trendurile</GBtn>
        </div>
      )}
    </div>
  );
}

// ═════════════════════════════════════════════════════════════════════════════
// CALENDAR
// ═════════════════════════════════════════════════════════════════════════════
function CalTab({T,onSave,brand}) {
  const [bizName,setBizName]=useState(brand?.bizName||"");
  const [bizType,setBizType]=useState(brand?.bizType||"");
  const [loading,setLoading]=useState(false);
  const [data,setData]=useState(null);
  const [err,setErr]=useState("");

  async function gen(){
    if(!bizName.trim()) return;
    setLoading(true);setErr("");setData(null);
    const dc=getDateContext();
    const p=
      "Calendar saptamanal "+bizName+(bizType?" "+bizType:"")+", "+dc.complet+".\n"+
      "Raspunde DOAR cu JSON:\n"+
      "{\"theme\":\"tema scurta "+dc.complet+"\",\"goal\":\"obiectiv scurt\","+
      "\"d1\":\"Luni\",\"d1pl\":\"TikTok\",\"d1t\":\"18:30\",\"d1i\":\"idee scurta "+bizName+"\",\"d1h\":\"hook\",\"d1tp\":\"Educational\",\"d1hot\":\"da\","+
      "\"d2\":\"Marti\",\"d2pl\":\"Instagram Reels\",\"d2t\":\"12:00\",\"d2i\":\"\",\"d2h\":\"\",\"d2tp\":\"BTS\",\"d2hot\":\"nu\","+
      "\"d3\":\"Miercuri\",\"d3pl\":\"TikTok\",\"d3t\":\"19:00\",\"d3i\":\"\",\"d3h\":\"\",\"d3tp\":\"Divertisment\",\"d3hot\":\"nu\","+
      "\"d4\":\"Joi\",\"d4pl\":\"Instagram Reels\",\"d4t\":\"17:00\",\"d4i\":\"\",\"d4h\":\"\",\"d4tp\":\"Vanzare\",\"d4hot\":\"da\","+
      "\"d5\":\"Vineri\",\"d5pl\":\"TikTok\",\"d5t\":\"20:00\",\"d5i\":\"\",\"d5h\":\"\",\"d5tp\":\"Vanzare\",\"d5hot\":\"da\","+
      "\"d6\":\"Sambata\",\"d6pl\":\"Instagram Stories\",\"d6t\":\"11:00\",\"d6i\":\"\",\"d6h\":\"\",\"d6tp\":\"Comunitate\",\"d6hot\":\"nu\","+
      "\"d7\":\"Duminica\",\"d7pl\":\"YouTube Shorts\",\"d7t\":\"16:00\",\"d7i\":\"\",\"d7h\":\"\",\"d7tp\":\"Educational\",\"d7hot\":\"nu\","+
      "\"tip1\":\"sfat scurt\",\"tip2\":\"sfat2\",\"tip3\":\"sfat3\"}";
    try{
      const r=await callAI(p);setData(r);
      if(onSave) onSave({id:Date.now(),type:"calendar",bizName,bizType,
        theme:r.theme||"",goal:r.goal||"",
        summary:[1,2,3,4,5,6,7].map(i=>r["d"+i]?r["d"+i]+" "+r["d"+i+"t"]+" — "+r["d"+i+"i"]:null).filter(Boolean).join("\n"),
        date:new Date().toLocaleDateString("ro-RO")});
    }catch(e){setErr(e.message||"Eroare. Încearcă din nou.");}
    finally{setLoading(false);}
  }

  const PC={TikTok:"#ff2d55","Instagram Reels":"#e1306c","YouTube Shorts":"#ff0000","Instagram Stories":"#c13584"};
  const TC={Educational:T.teal,BTS:T.acc2,Divertisment:T.gold,Vanzare:T.green,Comunitate:T.pink};
  const posts=data?[1,2,3,4,5,6,7].map(i=>({day:data["d"+i],platform:data["d"+i+"pl"],time:data["d"+i+"t"],idea:data["d"+i+"i"],hook:data["d"+i+"h"],type:data["d"+i+"tp"],hot:data["d"+i+"hot"]==="da"})).filter(p=>p.day):[];

  if(loading) return <Dots label={"Generez calendarul pentru "+bizName+"..."} T={T}/>;

  return (
    <div>
      {!data&&(
        <div style={{display:"flex",flexDirection:"column",gap:"14px",marginBottom:"16px"}}>
          <div><Lbl color={T.muted}>Numele afacerii</Lbl><MInput value={bizName} onChange={e=>setBizName(e.target.value)} placeholder="Numele afacerii tale" T={T}/></div>
          <div><Lbl color={T.muted}>Tipul afacerii (optional)</Lbl><BizSearch value={bizType} onChange={setBizType} T={T}/></div>
          <PBtn T={T} onClick={gen} disabled={!bizName.trim()} full>Generează Calendar →</PBtn>
        </div>
      )}
      {err&&<ErrBox T={T} msg={err} retry={gen}/>}
      {data&&(
        <div style={{animation:"vcpop 0.3s ease"}}>
          <div style={{background:`linear-gradient(135deg,${T.acc}10,${T.pink}08)`,border:`1px solid ${T.acc}20`,borderRadius:"16px",padding:"14px 16px",marginBottom:"14px",display:"flex",justifyContent:"space-between",alignItems:"center"}}>
            <div><Lbl color={T.acc}>Tema saptamanii</Lbl><p style={{margin:"0 0 3px",fontSize:"16px",fontWeight:700}}>✨ {data.theme}</p><p style={{margin:0,fontSize:"13px",color:T.muted}}>🎯 {data.goal}</p></div>
            <GBtn T={T} sm onClick={()=>setData(null)}>↩ Nou</GBtn>
          </div>
          {posts.map((p,i)=>(
            <div key={i} style={{background:T.card,border:`1px solid ${T.bord}`,borderLeft:`4px solid ${p.hot?T.pink:T.acc}`,borderRadius:"14px",padding:"14px 16px",marginBottom:"10px",boxShadow:`0 2px 12px ${T.shadow}`}}>
              <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"8px"}}>
                <div style={{display:"flex",gap:"10px",alignItems:"center"}}>
                  <div style={{textAlign:"center",minWidth:"50px"}}>
                    <div style={{fontSize:"11px",fontWeight:700,color:T.txt2}}>{p.day}</div>
                    <div style={{fontSize:"18px",fontWeight:800,color:T.acc,lineHeight:1.1}}>{p.time}</div>
                  </div>
                  <div style={{display:"flex",gap:"5px",flexWrap:"wrap"}}>
                    <span style={{fontSize:"10px",padding:"3px 8px",borderRadius:"20px",background:`${PC[p.platform]||"#333"}20`,color:PC[p.platform]||"#888",fontWeight:600}}>{p.platform}</span>
                    <span style={{fontSize:"10px",padding:"3px 8px",borderRadius:"20px",background:`${TC[p.type]||T.acc}15`,color:TC[p.type]||T.acc,fontWeight:600}}>{p.type}</span>
                  </div>
                </div>
                {p.hot&&<span style={{fontSize:"18px"}}>🔥</span>}
              </div>
              <p style={{margin:"0 0 4px",fontSize:"14px",fontWeight:600,color:T.txt}}>{p.idea}</p>
              <p style={{margin:0,fontSize:"12px",color:T.acc,fontStyle:"italic"}}>"{p.hook}"</p>
            </div>
          ))}
          <MCard T={T} accent={T.green} label="Sfaturi saptamana">
            {[data.tip1,data.tip2,data.tip3].filter(Boolean).map((t,i)=>(
              <div key={i} style={{display:"flex",gap:"12px",marginBottom:"10px"}}>
                <span style={{background:T.green,color:"#fff",borderRadius:"50%",width:"22px",height:"22px",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:700,flexShrink:0}}>{i+1}</span>
                <span style={{fontSize:"13px",color:T.txt2,lineHeight:1.5}}>{t}</span>
              </div>
            ))}
          </MCard>
        </div>
      )}
    </div>
  );
}

// ═════════════════════════════════════════════════════════════════════════════
// ISTORIC
// ═════════════════════════════════════════════════════════════════════════════
function HistTab({T,history,onDelete,favs,toggleFav}) {
  const [exp,setExp]=useState(null);
  const [cop,setCop]=useState(null);
  const [activeTab,setActiveTab]=useState("scripturi");
  const [showFavsOnly,setShowFavsOnly]=useState(false);

  const SECTIONS=[
    {id:"scripturi",icon:"⚡",label:"Scripturi",color:T.acc},
    {id:"calendar", icon:"📅",label:"Calendare",color:T.teal},
    {id:"stories",  icon:"📸",label:"Stories",  color:T.pink},
    {id:"creatori", icon:"🌟",label:"Creatori",  color:T.gold},
  ];
  const byType={
    scripturi:history.filter(x=>!x.type||x.type==="script"),
    calendar: history.filter(x=>x.type==="calendar"),
    stories:  history.filter(x=>x.type==="story"),
    creatori: history.filter(x=>x.type==="creator"),
  };
  const base    = byType[activeTab]||[];
  const current = showFavsOnly ? base.filter(x=>favs.includes(x.id)) : base;
  const activeCol=SECTIONS.find(s=>s.id===activeTab)?.color||T.acc;
  const totalFavs = history.filter(x=>favs.includes(x.id)).length;

  function copyItem(item) {
    let text="";
    if(item.type==="story") text="STORY: "+(item.storyType||"")+"\nTitlu: "+(item.titlu||"")+"\n\nCE FILMEZI:\n"+(item.ce_filmezi||"")+"\n\nOVERLAY: "+(item.overlay||"")+"\nSTICKER: "+(item.sticker||"")+"\nCTA: "+(item.cta||"");
    else if(item.type==="calendar") text="CALENDAR: "+(item.bizName||"")+"\n"+(item.summary||"");
    else if(item.type==="creator") text="CREATORI: "+(item.product||"")+"\n"+(item.intro||"");
    else text='HOOK: "'+(item.hook||"")+'"\n\nSCRIPT:\n'+(item.script||"")+"\n\nCAPTION:\n"+(item.caption||"");
    navigator.clipboard.writeText(text);
    setCop(item.id);setTimeout(()=>setCop(null),2000);
  }

  if(!history.length) return (
    <div style={{textAlign:"center",padding:"60px 20px",animation:"vcpop 0.3s ease"}}>
      <div style={{
        width:"90px",height:"90px",borderRadius:"28px",
        background:`linear-gradient(135deg,${T.acc}20,${T.pink}10)`,
        border:`1.5px solid ${T.acc}25`,
        display:"flex",alignItems:"center",justifyContent:"center",
        fontSize:"40px",margin:"0 auto 20px",
        boxShadow:`0 8px 32px ${T.acc}20`,
      }}>🗂</div>
      <p style={{fontSize:"17px",fontWeight:700,color:T.txt,margin:"0 0 8px"}}>Nicio generare inca</p>
      <p style={{fontSize:"13px",color:T.muted,margin:"0 0 24px",lineHeight:1.6}}>Generează primul tau script, story sau calendar — se salvează automat aici.</p>
      <div style={{display:"inline-flex",alignItems:"center",gap:"8px",padding:"10px 18px",borderRadius:"20px",background:`${T.acc}12`,border:`1px solid ${T.acc}25`,color:T.acc,fontSize:"13px",fontWeight:600}}>
        ⚡ Mergi la Generator
      </div>
    </div>
  );

  return (
    <div>
      {/* Sections + favs filter */}
      <div style={{display:"flex",gap:"6px",marginBottom:"12px",overflowX:"auto",padding:"2px"}}>
        {SECTIONS.map(s=>{
          const cnt=byType[s.id]?.length||0;
          const active=activeTab===s.id;
          return (
            <button key={s.id} onClick={()=>{setActiveTab(s.id);setShowFavsOnly(false);}} style={{
              display:"flex",alignItems:"center",gap:"6px",
              padding:"10px 14px",borderRadius:"12px",border:"none",flexShrink:0,
              background:active?`${s.color}18`:T.faint,
              borderBottom:active?`3px solid ${s.color}`:"3px solid transparent",
              color:active?s.color:T.muted,fontSize:"13px",fontWeight:active?700:400,
              cursor:"pointer",fontFamily:"inherit",minHeight:"52px"}}>
              <span style={{fontSize:"17px"}}>{s.icon}</span>
              <span>{s.label}</span>
              {cnt>0&&<span style={{fontSize:"10px",padding:"2px 7px",borderRadius:"20px",
                background:active?`${s.color}25`:T.bord,color:active?s.color:T.muted,fontWeight:700}}>{cnt}</span>}
            </button>
          );
        })}
      </div>

      {/* Favs filter */}
      {totalFavs > 0 && (
        <button onClick={()=>setShowFavsOnly(f=>!f)} style={{
          display:"flex",alignItems:"center",gap:"8px",
          padding:"9px 16px",borderRadius:"20px",marginBottom:"14px",
          border:`1.5px solid ${showFavsOnly?T.gold:T.bord}`,
          background:showFavsOnly?`${T.gold}15`:T.faint,
          color:showFavsOnly?T.gold:T.muted,
          fontSize:"12px",fontWeight:showFavsOnly?700:400,
          cursor:"pointer",fontFamily:"inherit",
        }}>
          <span>{showFavsOnly?"⭐":"☆"}</span>
          <span>{showFavsOnly?"Toate":"Doar favorite"}</span>
          <span style={{padding:"1px 7px",borderRadius:"20px",background:`${T.gold}20`,color:T.gold,fontSize:"10px",fontWeight:700}}>{totalFavs}</span>
        </button>
      )}

      {current.length===0&&(
        <div style={{textAlign:"center",padding:"48px 0",color:T.muted}}>
          <div style={{fontSize:"36px",marginBottom:"10px"}}>{showFavsOnly?"⭐":SECTIONS.find(s=>s.id===activeTab)?.icon}</div>
          <p style={{fontSize:"14px",margin:0}}>{showFavsOnly?"Niciun favorit in aceasta sectiune":"Nimic salvat în aceasta sectiune"}</p>
        </div>
      )}

      {current.map(item=>(
        <div key={item.id} style={{background:T.card,border:`1px solid ${T.bord}`,borderLeft:`4px solid ${activeCol}`,borderRadius:"14px",overflow:"hidden",marginBottom:"10px",boxShadow:`0 2px 12px ${T.shadow}`}}>
          <div style={{padding:"14px 16px",display:"flex",justifyContent:"space-between",alignItems:"center",cursor:"pointer"}} onClick={()=>setExp(exp===item.id?null:item.id)}>
            <div style={{flex:1,minWidth:0}}>
              <p style={{margin:"0 0 4px",fontSize:"15px",fontWeight:700,color:T.txt}}>{item.bizName||item.product||"—"}</p>
              <div style={{display:"flex",gap:"5px",flexWrap:"wrap"}}>
                {item.bizType&&<span style={{fontSize:"11px",color:activeCol,fontWeight:600}}>{item.bizType}</span>}
                {item.platform&&<><span style={{color:T.bord,fontSize:"11px"}}>·</span><span style={{fontSize:"13px",color:T.muted}}>{item.platform}</span></>}
                {item.goal&&<><span style={{color:T.bord,fontSize:"11px"}}>·</span><span style={{fontSize:"13px",color:T.muted}}>{item.goal}</span></>}
                <span style={{color:T.bord,fontSize:"11px"}}>·</span>
                <span style={{fontSize:"13px",color:T.muted}}>{item.date}</span>
              </div>
            </div>
            <div style={{display:"flex",gap:"6px",alignItems:"center",flexShrink:0,marginLeft:"10px"}}>
              <button onClick={e=>{e.stopPropagation();toggleFav(item.id);}} style={{
                width:"40px",height:"40px",borderRadius:"10px",
                border:`1px solid ${favs.includes(item.id)?T.gold+"60":T.bord}`,
                background:favs.includes(item.id)?`${T.gold}15`:"transparent",
                color:favs.includes(item.id)?T.gold:T.muted,
                fontSize:"18px",cursor:"pointer",
                display:"flex",alignItems:"center",justifyContent:"center",
                transition:"all 0.2s",
              }}>{favs.includes(item.id)?"⭐":"☆"}</button>
              <button onClick={e=>{e.stopPropagation();copyItem(item);}} style={{width:"40px",height:"40px",borderRadius:"10px",border:`1px solid ${T.bord}`,background:"transparent",color:cop===item.id?T.green:T.muted,fontSize:"16px",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"}}>{cop===item.id?"✓":"📋"}</button>
              <button onClick={e=>{e.stopPropagation();onDelete(item.id);}} style={{width:"40px",height:"40px",borderRadius:"10px",border:`1px solid ${T.bord}`,background:"transparent",color:T.muted,fontSize:"16px",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"}}>🗑</button>
              <span style={{color:T.muted,fontSize:"13px"}}>{exp===item.id?"▲":"▼"}</span>
            </div>
          </div>
          {exp===item.id&&(
            <div style={{padding:"0 16px 16px",borderTop:`1px solid ${T.bord}`}}>
              {(!item.type||item.type==="script")&&(
                <>
                  <div style={{marginTop:"14px",padding:"12px 14px",background:`${T.acc}0d`,borderLeft:`3px solid ${T.acc}`,borderRadius:"0 10px 10px 0",marginBottom:"12px"}}>
                    <Lbl color={T.acc}>Hook</Lbl>
                    <p style={{margin:0,fontSize:"16px",fontWeight:700,color:T.txt}}>"{item.hook}"</p>
                  </div>
                  {item.hook_b&&<div style={{marginBottom:"12px",padding:"10px 14px",background:`${T.pink}0d`,borderLeft:`3px solid ${T.pink}`,borderRadius:"0 10px 10px 0"}}><Lbl color={T.pink}>Hook B</Lbl><p style={{margin:0,fontSize:"14px",color:T.txt,fontStyle:"italic"}}>"{item.hook_b}"</p></div>}
                  <pre style={{margin:"0 0 10px",fontFamily:"'Space Mono'",fontSize:"11px",lineHeight:1.7,color:T.txt2,whiteSpace:"pre-wrap",wordBreak:"break-word"}}>{item.script}</pre>
                  <p style={{margin:0,fontSize:"13px",color:T.muted}}>{item.caption}</p>
                </>
              )}
              {item.type==="story"&&(
                <>
                  <div style={{marginTop:"14px",padding:"12px 14px",background:`${T.pink}0d`,borderLeft:`3px solid ${T.pink}`,borderRadius:"0 10px 10px 0",marginBottom:"10px"}}><Lbl color={T.pink}>Titlu</Lbl><p style={{margin:0,fontSize:"16px",fontWeight:700,color:T.txt}}>{item.titlu}</p></div>
                  <div style={{marginBottom:"10px"}}><Lbl color={T.muted}>Ce filmezi</Lbl><p style={{margin:0,fontSize:"13px",color:T.txt2,lineHeight:1.65}}>{item.ce_filmezi}</p></div>
                  <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"8px",marginBottom:"10px"}}>
                    <div style={{padding:"10px 12px",background:T.faint,borderRadius:"10px"}}><Lbl color={T.muted}>Overlay</Lbl><p style={{margin:0,fontSize:"13px",fontWeight:700,color:T.gold}}>"{item.overlay}"</p></div>
                    <div style={{padding:"10px 12px",background:T.faint,borderRadius:"10px"}}><Lbl color={T.muted}>Sticker</Lbl><p style={{margin:0,fontSize:"12px",color:T.teal}}>{item.sticker}</p></div>
                  </div>
                  <div style={{padding:"10px 12px",background:`${T.acc}0d`,borderRadius:"10px",fontSize:"14px",color:T.acc,fontWeight:500}}>👉 {item.cta}</div>
                </>
              )}
              {item.type==="calendar"&&(
                <div style={{marginTop:"14px"}}><Lbl color={T.teal}>Tema</Lbl><p style={{margin:"0 0 8px",fontSize:"15px",fontWeight:700,color:T.txt}}>✨ {item.theme}</p><p style={{margin:0,fontSize:"13px",color:T.muted}}>{item.goal}</p></div>
              )}
              {item.type==="creator"&&(
                <div style={{marginTop:"14px"}}><Lbl color={T.gold}>Strategie</Lbl><p style={{margin:"0 0 8px",fontSize:"13px",color:T.txt2,lineHeight:1.6}}>{item.intro}</p><p style={{margin:0,fontSize:"13px",color:T.muted,fontStyle:"italic"}}>{item.strategie}</p></div>
              )}
            </div>
          )}
        </div>
      ))}
    </div>
  );
}

// ═════════════════════════════════════════════════════════════════════════════
// STORIES
// ═════════════════════════════════════════════════════════════════════════════
function StoryTab({T,onSave,brand}) {
  const [bizName,setBizName]     = useState(brand?.bizName||"");
  const [bizType,setBizType]     = useState(brand?.bizType||"");
  const [audience,setAudience]   = useState("");
  const [goal,setGoal]           = useState("");
  const [offer,setOffer]         = useState("");
  const [tone,setTone]           = useState(brand?.tone||"");
  const [storyTypes,setStoryTypes]=useState([]);
  const [loading,setLoading]     = useState(false);
  const [result,setResult]       = useState(null);
  const [err,setErr]             = useState("");
  const [copied,setCopied]       = useState(false);

  const STORY_GOALS=["Vanzari directe","Crestere followeri","Brand awareness","Generare lead-uri","Fidelizare clienti","Educatie / informatii"];
  const STORY_TONES=["Casual si prietenos","Profesional","Haios si relaxat","Inspirational","Urgent / FOMO","Intim si sincer"];
  const ALL_TYPES=[
    {id:"bts",       icon:"🎬",label:"Behind the scenes",  color:"#fbbf24"},
    {id:"produs",    icon:"🛍️",label:"Prezentare produs",   color:"#8b5cf6"},
    {id:"social",    icon:"⭐",label:"Social proof",        color:"#34d399"},
    {id:"edu",       icon:"📚",label:"Educativ",            color:"#2dd4bf"},
    {id:"oferta",    icon:"🔥",label:"Oferta / Promotie",   color:"#f472b6"},
    {id:"divertis",  icon:"😄",label:"Divertisment",        color:"#f97316"},
    {id:"comunitate",icon:"💬",label:"Comunitate",          color:"#6366f1"},
    {id:"qa",        icon:"❓",label:"Q&A / Poll",          color:"#a855f7"},
    {id:"reveal",    icon:"✨",label:"Inainte / Dupa",      color:"#06b6d4"},
    {id:"colisaj",   icon:"📸",label:"Zi din viata mea",    color:"#ec4899"},
  ];

  function toggleType(id){setStoryTypes(p=>p.includes(id)?p.filter(x=>x!==id):[...p,id]);}
  const canGen=bizName.trim()&&bizType&&goal;

  async function gen(){
    if(!canGen) return;
    setLoading(true);setErr("");setResult(null);
    const dc=getDateContext();
    const selectedLabels=storyTypes.length>0
      ?storyTypes.map(id=>ALL_TYPES.find(t=>t.id===id)?.label).filter(Boolean).join(", ")
      :"tipul cel mai potrivit pentru afacerea respectiva";
    const p=
      "Story Instagram perfecta pentru "+bizName+" "+bizType+", "+dc.complet+".\n"+
      "Obiectiv: "+goal+(audience?", public: "+audience:"")+(offer?", produs: "+offer:"")+(tone?", ton: "+tone:"")+".\n"+
      "Tip preferat: "+selectedLabels+".\n"+
      "Raspunde DOAR cu JSON:\n"+
      "{\"tip\":\"tipul\",\"titlu\":\"titlu scurt\",\"ce_filmezi\":\"ce filmezi concret\",\"overlay\":\"max 5 cuvinte\",\"sticker\":\"sticker+text\",\"cta\":\"cta scurt\",\"sfat_filmare\":\"sfat scurt\",\"de_ce\":\"max 8 cuvinte\"}";
    try{
      const r=await callAI(p);
      if(!r.ce_filmezi&&!r.titlu) throw new Error("Raspuns incomplet. Încearcă din nou.");
      setResult(r);
      if(onSave) onSave({id:Date.now(),type:"story",bizName,bizType,goal,
        storyType:r.tip||"",titlu:r.titlu||"",ce_filmezi:r.ce_filmezi||"",
        overlay:r.overlay||"",sticker:r.sticker||"",cta:r.cta||"",de_ce:r.de_ce||"",
        date:new Date().toLocaleDateString("ro-RO")});
    }catch(e){setErr(e.message||"Eroare. Încearcă din nou.");}
    finally{setLoading(false);}
  }

  function copyStory(){
    if(!result) return;
    navigator.clipboard.writeText("STORY: "+result.tip+"\nTitlu: "+result.titlu+"\n\nCE FILMEZI:\n"+result.ce_filmezi+"\n\nOVERLAY: "+result.overlay+"\nSTICKER: "+result.sticker+"\nCTA: "+result.cta+"\n\nSFAT: "+result.sfat_filmare);
    setCopied(true);setTimeout(()=>setCopied(false),2500);
  }

  const selType=storyTypes.length===1?ALL_TYPES.find(t=>t.id===storyTypes[0]):null;
  const selColor=selType?.color||T.acc;

  if(loading) return <Dots label={"Creez story perfecta pentru "+bizName+"..."} T={T}/>;

  if(result) return (
    <div style={{animation:"vcpop 0.3s ease"}}>
      <div style={{display:"flex",justifyContent:"space-between",alignItems:"flex-start",marginBottom:"14px"}}>
        <div>
          <h2 style={{margin:0,fontSize:"20px",fontWeight:800}}>{bizName}</h2>
          <p style={{margin:"4px 0 0",color:T.muted,fontSize:"12px"}}>{goal} · {result.tip}</p>
        </div>
        <div style={{display:"flex",gap:"8px"}}>
          <GBtn T={T} sm onClick={()=>setResult(null)}>↩ Nou</GBtn>
          <GBtn T={T} sm onClick={gen}>↻ Alt story</GBtn>
        </div>
      </div>

      <div style={{display:"inline-flex",alignItems:"center",gap:"8px",padding:"8px 16px",borderRadius:"20px",background:`${selColor}15`,border:`1px solid ${selColor}30`,marginBottom:"14px"}}>
        <span style={{fontSize:"18px"}}>{ALL_TYPES.find(t=>t.label===result.tip)?.icon||"📸"}</span>
        <span style={{fontSize:"14px",fontWeight:700,color:selColor}}>{result.tip}</span>
      </div>

      <div style={{background:`linear-gradient(135deg,${T.acc}18,${T.pink}12)`,border:`1px solid ${T.acc}30`,borderRadius:"16px",padding:"18px",marginBottom:"12px"}}>
        <Lbl color={T.acc}>Titlul story-ului</Lbl>
        <p style={{margin:"0 0 12px",fontSize:"clamp(19px,4vw,24px)",fontWeight:800,lineHeight:1.25,color:T.txt}}>{result.titlu}</p>
        <div style={{padding:"10px 12px",background:`${T.acc}12`,borderLeft:`3px solid ${T.acc}`,borderRadius:"0 10px 10px 0",fontSize:"13px",color:T.txt2}}>💡 {result.de_ce}</div>
      </div>

      <MCard T={T} accent={T.teal} label="Ce filmezi — pas cu pas">
        <p style={{margin:0,fontSize:"14px",lineHeight:1.75,color:T.txt2}}>{result.ce_filmezi}</p>
      </MCard>

      <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"10px",marginBottom:"12px"}}>
        <div style={{background:T.card,border:`1px solid ${T.bord}`,borderLeft:`4px solid ${T.gold}`,borderRadius:"14px",padding:"14px"}}>
          <Lbl color={T.gold}>Text Overlay</Lbl>
          <p style={{margin:0,fontSize:"18px",fontWeight:800,color:T.gold,lineHeight:1.2}}>"{result.overlay}"</p>
        </div>
        <div style={{background:T.card,border:`1px solid ${T.bord}`,borderLeft:`4px solid ${T.teal}`,borderRadius:"14px",padding:"14px"}}>
          <Lbl color={T.teal}>Sticker / Poll</Lbl>
          <p style={{margin:0,fontSize:"13px",color:T.teal,fontWeight:600,lineHeight:1.4}}>{result.sticker}</p>
        </div>
      </div>

      <div style={{background:`${T.pink}10`,border:`1px solid ${T.pink}30`,borderRadius:"14px",padding:"14px 16px",marginBottom:"12px",display:"flex",alignItems:"center",gap:"12px"}}>
        <span style={{fontSize:"22px"}}>👉</span>
        <div>
          <Lbl color={T.pink}>Call to Action</Lbl>
          <p style={{margin:0,fontSize:"16px",fontWeight:700,color:T.txt}}>{result.cta}</p>
        </div>
      </div>

      <div style={{background:`${T.gold}0d`,border:`1px solid ${T.gold}25`,borderRadius:"14px",padding:"12px 16px",marginBottom:"14px"}}>
        <Lbl color={T.gold}>Sfat de filmare</Lbl>
        <p style={{margin:0,fontSize:"13px",color:T.txt2,lineHeight:1.6}}>🎬 {result.sfat_filmare}</p>
      </div>

      {err&&<ErrBox T={T} msg={err} retry={gen}/>}

      <button onClick={copyStory} style={{
        width:"100%",padding:"16px",borderRadius:"14px",
        border:copied?`1px solid ${T.green}50`:"none",
        background:copied?`${T.green}12`:`linear-gradient(135deg,${T.acc},${T.acc2})`,
        color:copied?T.green:"#fff",fontSize:"15px",fontWeight:700,
        cursor:"pointer",fontFamily:"inherit",minHeight:"54px",
        boxShadow:copied?"none":`0 5px 24px ${T.acc}45`,transition:"all 0.3s"}}>
        {copied?"✓ Story copiata!":"📋 Copiază Story Completa"}
      </button>
    </div>
  );

  return (
    <div style={{display:"flex",flexDirection:"column",gap:"18px",animation:"vcpop 0.3s ease"}}>
      <div style={{background:`linear-gradient(135deg,${T.acc}12,${T.pink}08)`,border:`1px solid ${T.acc}25`,borderRadius:"16px",padding:"16px"}}>
        <Lbl color={T.acc}>Informatii afacere</Lbl>
        <div style={{display:"flex",flexDirection:"column",gap:"10px"}}>
          <MInput value={bizName} onChange={e=>setBizName(e.target.value)} placeholder="Numele afacerii tale" T={T} big/>
          <BizSearch value={bizType} onChange={setBizType} T={T}/>
        </div>
      </div>
      <div><Lbl color={T.muted}>Publicul tău (optional)</Lbl><MInput value={audience} onChange={e=>setAudience(e.target.value)} placeholder="ex: femei 25-40 ani, mame, tineri..." T={T}/></div>
      <div><Lbl color={T.muted}>Produs / Serviciu promovat (optional)</Lbl><MInput value={offer} onChange={e=>setOffer(e.target.value)} placeholder="ex: vopsit par, abonament gym..." T={T}/></div>
      <div>
        <Lbl color={T.muted}>Obiectivul story-ului</Lbl>
        <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"8px"}}>
          {STORY_GOALS.map(g=>(
            <button key={g} onClick={()=>setGoal(g)} style={{padding:"12px",borderRadius:"12px",minHeight:"52px",border:`1.5px solid ${goal===g?T.acc:T.bord}`,background:goal===g?`${T.acc}12`:T.faint,color:goal===g?T.acc:T.txt2,fontSize:"12px",fontWeight:goal===g?600:400,cursor:"pointer",fontFamily:"inherit",textAlign:"left"}}>{g}</button>
          ))}
        </div>
      </div>
      <div>
        <Lbl color={T.muted}>Tonul comunicarii (optional)</Lbl>
        <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"8px"}}>
          {STORY_TONES.map(t=>(
            <button key={t} onClick={()=>setTone(prev=>prev===t?"":t)} style={{padding:"11px 12px",borderRadius:"12px",minHeight:"56px",border:`1.5px solid ${tone===t?T.pink:T.bord}`,background:tone===t?`${T.pink}12`:T.faint,color:tone===t?T.pink:T.txt2,fontSize:"12px",fontWeight:tone===t?600:400,cursor:"pointer",fontFamily:"inherit",textAlign:"left"}}>{t}</button>
          ))}
        </div>
      </div>
      <div>
        <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"8px"}}>
          <Lbl color={T.muted}>Tipul de story</Lbl>
          <span style={{fontSize:"13px",color:T.muted}}>{storyTypes.length===0?"orice tip":storyTypes.length+" selectate"}</span>
        </div>
        <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"8px"}}>
          {ALL_TYPES.map(st=>{
            const sel=storyTypes.includes(st.id);
            return (
              <button key={st.id} onClick={()=>toggleType(st.id)} style={{
                padding:"12px",borderRadius:"12px",minHeight:"80px",
                border:`1.5px solid ${sel?st.color:T.bord}`,
                background:sel?`${st.color}12`:T.faint,
                color:sel?st.color:T.txt2,cursor:"pointer",fontFamily:"inherit",
                textAlign:"left",display:"flex",alignItems:"flex-start",gap:"8px"}}>
                <span style={{fontSize:"18px",flexShrink:0}}>{st.icon}</span>
                <div style={{flex:1}}>
                  <div style={{fontSize:"12px",fontWeight:sel?700:500}}>{st.label}</div>
                </div>
                {sel&&<span style={{fontSize:"14px",color:st.color,flexShrink:0}}>✓</span>}
              </button>
            );
          })}
        </div>
        {storyTypes.length>0&&<button onClick={()=>setStoryTypes([])} style={{marginTop:"8px",padding:"8px 14px",borderRadius:"10px",border:`1px solid ${T.bord}`,background:"transparent",color:T.muted,fontSize:"12px",cursor:"pointer",fontFamily:"inherit"}}>✕ Resetează selectia</button>}
      </div>
      {err&&<ErrBox T={T} msg={err} retry={gen}/>}
      <PBtn T={T} onClick={gen} disabled={!canGen} full>📸 Generează Story Perfecta →</PBtn>
    </div>
  );
}

// ═════════════════════════════════════════════════════════════════════════════
// CREATORI
// ═════════════════════════════════════════════════════════════════════════════
function CreTab({T,onSave,brand}) {
  const [product,setProduct]   = useState(brand?.bizName||"");
  const [bizType,setBizType]   = useState(brand?.bizType||"");
  const [budget,setBudget]     = useState("");
  const [goal,setGoal]         = useState("");
  const [audience,setAudience] = useState("");
  const [location,setLocation] = useState(brand?.city||"");
  const [collab,setCollab]     = useState("");
  const [exclusiv,setExclusiv] = useState("");
  const [loading,setLoading]   = useState(false);
  const [data,setData]         = useState(null);
  const [err,setErr]           = useState("");

  const BUDGETS=["Sub 100 RON","100-300 RON","300-500 RON","500-1.000 RON","1.000-3.000 RON","Peste 3.000 RON","Produs gratuit / barter"];
  const GOALS=["Crestere followeri","Vanzari directe","Brand awareness","Lansare produs","Generare recenzii","Trafic website"];
  const COLLABS=["Post simplu pe feed","Reel / TikTok video","Story 24h","Review detaliat","Pachet complet","Live stream","Affiliate pe termen lung"];
  const EXCLUSIVS=["Nu conteaza","Fara competitori directi","Exclusivitate pe nisa","Exclusivitate totala"];

  const canGen=product.trim()&&budget&&goal;

  async function gen(){
    if(!canGen) return;
    setLoading(true);setErr("");setData(null);
    const dc=getDateContext();
    const p=
      "Influencer marketing Romania, "+dc.complet+". "+
      "Produs: "+product+(bizType?", "+bizType:"")+", buget: "+budget+", obiectiv: "+goal+
      (audience?", public: "+audience:"")+(location?", zona: "+location:"")+
      (collab?", collab: "+collab:"")+(exclusiv?", exclusiv: "+exclusiv:"")+".\n"+
      "Raspunde DOAR cu JSON:\n"+
      "{\"intro\":\"intro scurt "+dc.an+"\",\"strategie_generala\":\"strategie scurta buget "+budget+"\","+
      "\"c1t\":\"Micro (5k-50k)\",\"c1n\":\"nisa\",\"c1w\":\"de ce max 8 cuvinte\",\"c1f\":\"unde gasesti\",\"c1sel\":\"criterii scurte\",\"c1p\":\"mesaj natural romana\",\"c1b\":\"buget "+dc.an+"\",\"c1r\":\"rezultat\",\"c1kpi\":\"kpi\","+
      "\"c2t\":\"Mid-tier (50k-500k)\",\"c2n\":\"\",\"c2w\":\"\",\"c2f\":\"\",\"c2sel\":\"\",\"c2p\":\"\",\"c2b\":\"\",\"c2r\":\"\",\"c2kpi\":\"\","+
      "\"c3t\":\"Nano (1k-5k)\",\"c3n\":\"\",\"c3w\":\"\",\"c3f\":\"\",\"c3sel\":\"\",\"c3p\":\"\",\"c3b\":\"\",\"c3r\":\"\",\"c3kpi\":\"\","+
      "\"i1\":\"idee1\",\"i2\":\"idee2\",\"i3\":\"idee3\",\"i4\":\"idee4\","+
      "\"r1\":\"red flag1\",\"r2\":\"red flag2\",\"r3\":\"red flag3\","+
      "\"contract\":\"ce includa scurt\",\"timing\":\"moment optim "+dc.complet+"\"}";
    try{
      const r=await callAI(p);setData(r);
      if(onSave) onSave({id:Date.now(),type:"creator",product,bizType,budget,goal,
        intro:r.intro||"",strategie:r.strategie_generala||"",
        date:new Date().toLocaleDateString("ro-RO")});
    }catch(e){setErr(e.message||"Eroare. Încearcă din nou.");}
    finally{setLoading(false);}
  }

  const TC={"Micro (5k-50k)":T.green,"Mid-tier (50k-500k)":T.acc,"Nano (1k-5k)":T.gold};
  const creators=data?[1,2,3].map(i=>({tier:data["c"+i+"t"],niche:data["c"+i+"n"],why:data["c"+i+"w"],find:data["c"+i+"f"],sel:data["c"+i+"sel"],pitch:data["c"+i+"p"],budget:data["c"+i+"b"],result:data["c"+i+"r"],kpi:data["c"+i+"kpi"]})).filter(c=>c.tier):[];

  if(loading) return <Dots label="Generez strategia de influencer marketing..." T={T}/>;

  return (
    <div>
      {!data?(
        <div style={{display:"flex",flexDirection:"column",gap:"18px",animation:"vcpop 0.3s ease"}}>
          <div style={{background:`linear-gradient(135deg,${T.acc}12,${T.pink}08)`,border:`1px solid ${T.acc}25`,borderRadius:"16px",padding:"16px"}}>
            <Lbl color={T.acc}>Ce promovezi?</Lbl>
            <MTextarea value={product} onChange={e=>setProduct(e.target.value)} placeholder="Descrie produsul/serviciul in detaliu..." T={T} rows={3}/>
            <div style={{marginTop:"10px"}}><BizSearch value={bizType} onChange={setBizType} T={T}/></div>
          </div>
          <div><Lbl color={T.muted}>Buget per colaborare</Lbl><div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"8px"}}>{BUDGETS.map(b=><button key={b} onClick={()=>setBudget(b)} style={{padding:"12px",borderRadius:"12px",minHeight:"52px",border:`1.5px solid ${budget===b?T.acc:T.bord}`,background:budget===b?`${T.acc}12`:T.faint,color:budget===b?T.acc:T.txt2,fontSize:"12px",fontWeight:budget===b?600:400,cursor:"pointer",fontFamily:"inherit",textAlign:"left"}}>{b}</button>)}</div></div>
          <div><Lbl color={T.muted}>Obiectivul campaniei</Lbl><div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"8px"}}>{GOALS.map(g=><button key={g} onClick={()=>setGoal(g)} style={{padding:"12px",borderRadius:"12px",minHeight:"52px",border:`1.5px solid ${goal===g?T.pink:T.bord}`,background:goal===g?`${T.pink}12`:T.faint,color:goal===g?T.pink:T.txt2,fontSize:"12px",fontWeight:goal===g?600:400,cursor:"pointer",fontFamily:"inherit",textAlign:"left"}}>{g}</button>)}</div></div>
          <div><Lbl color={T.muted}>Publicul țintă (optional)</Lbl><MInput value={audience} onChange={e=>setAudience(e.target.value)} placeholder="ex: femei 30-45 ani, interesate de lifestyle..." T={T}/></div>
          <div><Lbl color={T.muted}>Zona geografica</Lbl><CitySearch value={location} onChange={setLocation} T={T}/></div>
          <div><Lbl color={T.muted}>Tipul de colaborare</Lbl><div style={{display:"flex",flexDirection:"column",gap:"8px"}}>{COLLABS.map(c=><button key={c} onClick={()=>setCollab(c)} style={{padding:"13px 16px",borderRadius:"12px",minHeight:"52px",border:`1.5px solid ${collab===c?T.gold:T.bord}`,background:collab===c?`${T.gold}12`:T.faint,color:collab===c?T.gold:T.txt2,fontSize:"13px",fontWeight:collab===c?600:400,cursor:"pointer",fontFamily:"inherit",textAlign:"left"}}>{c}</button>)}</div></div>
          <div><Lbl color={T.muted}>Clauza exclusivitate</Lbl><div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"8px"}}>{EXCLUSIVS.map(e=><button key={e} onClick={()=>setExclusiv(e)} style={{padding:"11px 12px",borderRadius:"12px",minHeight:"52px",border:`1.5px solid ${exclusiv===e?T.acc2:T.bord}`,background:exclusiv===e?`${T.acc2}12`:T.faint,color:exclusiv===e?T.acc2:T.txt2,fontSize:"12px",fontWeight:exclusiv===e?600:400,cursor:"pointer",fontFamily:"inherit"}}>{e}</button>)}</div></div>
          {err&&<ErrBox T={T} msg={err} retry={gen}/>}
          <PBtn T={T} onClick={gen} disabled={!canGen} full>🌟 Generează Strategie Influenceri →</PBtn>
        </div>
      ):(
        <div style={{animation:"vcpop 0.3s ease"}}>
          <div style={{display:"flex",justifyContent:"space-between",alignItems:"flex-start",marginBottom:"14px"}}>
            <div>
              <h3 style={{margin:0,fontSize:"16px",fontWeight:800}}>Strategie Influenceri</h3>
              <p style={{margin:"4px 0 0",fontSize:"13px",color:T.muted}}>{budget} · {goal}</p>
            </div>
            <GBtn T={T} sm onClick={()=>setData(null)}>↩ Nou</GBtn>
          </div>
          <div style={{background:T.faint,border:`1px solid ${T.bord}`,borderRadius:"14px",padding:"14px 16px",marginBottom:"14px"}}>
            <p style={{margin:"0 0 6px",fontSize:"13px",color:T.txt,lineHeight:1.6}}>{data.intro}</p>
            <p style={{margin:0,fontSize:"13px",color:T.muted,fontStyle:"italic"}}>{data.strategie_generala}</p>
          </div>
          {creators.map((c,i)=>(
            <div key={i} style={{background:T.card,border:`1px solid ${T.bord}`,borderLeft:`4px solid ${TC[c.tier]||T.acc}`,borderRadius:"14px",overflow:"hidden",marginBottom:"12px",boxShadow:`0 2px 12px ${T.shadow}`}}>
              <div style={{padding:"12px 16px",borderBottom:`1px solid ${T.bord}`,background:`${TC[c.tier]||T.acc}0a`,display:"flex",justifyContent:"space-between",alignItems:"center"}}>
                <span style={{fontSize:"15px",fontWeight:700,color:TC[c.tier]||T.acc}}>{c.tier}</span>
                <span style={{fontSize:"12px",padding:"4px 12px",borderRadius:"20px",background:`${TC[c.tier]||T.acc}15`,color:TC[c.tier]||T.acc,fontWeight:600}}>{c.budget}</span>
              </div>
              <div style={{padding:"14px 16px",display:"flex",flexDirection:"column",gap:"12px"}}>
                <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"10px"}}>
                  <div><Lbl color={T.muted}>Nisa exacta</Lbl><p style={{margin:0,fontSize:"13px",color:T.txt,fontWeight:500}}>{c.niche}</p></div>
                  <div><Lbl color={T.muted}>Rezultat estimat</Lbl><p style={{margin:0,fontSize:"13px",color:T.green,fontWeight:500}}>{c.result}</p></div>
                </div>
                <div><Lbl color={T.muted}>Unde ii gasesti</Lbl><p style={{margin:0,fontSize:"13px",color:T.txt2}}>{c.find}</p></div>
                {c.sel&&<div style={{padding:"10px 12px",background:`${T.gold}0d`,borderLeft:`3px solid ${T.gold}`,borderRadius:"0 10px 10px 0"}}><Lbl color={T.gold}>Criterii selectie</Lbl><p style={{margin:0,fontSize:"12px",color:T.txt2,lineHeight:1.6}}>{c.sel}</p></div>}
                {c.kpi&&<div><Lbl color={T.muted}>KPI-uri</Lbl><p style={{margin:0,fontSize:"12px",color:T.txt2}}>{c.kpi}</p></div>}
                <div style={{padding:"12px 14px",background:`${T.acc}0d`,borderLeft:`3px solid ${T.acc}`,borderRadius:"0 12px 12px 0"}}>
                  <Lbl color={T.acc}>Mesaj Contact — Copy/Paste</Lbl>
                  <p style={{margin:"0 0 10px",fontSize:"13px",color:T.txt,lineHeight:1.6,fontStyle:"italic"}}>{c.pitch}</p>
                  <CBtn T={T} text={c.pitch} label="Copiază mesajul"/>
                </div>
              </div>
            </div>
          ))}
          <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"10px",marginBottom:"10px"}}>
            <MCard T={T} accent={T.teal} label="Idei Campanie" mb="0">{[data.i1,data.i2,data.i3,data.i4].filter(Boolean).map((x,i)=><div key={i} style={{display:"flex",gap:"10px",marginBottom:"8px"}}><span style={{background:T.teal,color:"#fff",borderRadius:"50%",width:"22px",height:"22px",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:700,flexShrink:0}}>{i+1}</span><span style={{fontSize:"12px",color:T.txt2,lineHeight:1.5}}>{x}</span></div>)}</MCard>
            <MCard T={T} accent={T.red} label="Red Flags" mb="0">{[data.r1,data.r2,data.r3].filter(Boolean).map((x,i)=><div key={i} style={{display:"flex",gap:"8px",marginBottom:"8px"}}><span style={{color:T.red,fontSize:"16px"}}>✗</span><span style={{fontSize:"12px",color:T.txt2,lineHeight:1.5}}>{x}</span></div>)}</MCard>
          </div>
          {(data.contract||data.timing)&&(
            <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"10px",marginBottom:"10px"}}>
              {data.contract&&<MCard T={T} accent={T.acc2} label="Contract" mb="0"><p style={{margin:0,fontSize:"12px",color:T.txt2,lineHeight:1.6}}>{data.contract}</p></MCard>}
              {data.timing&&<MCard T={T} accent={T.pink} label="Cel mai bun moment" mb="0"><p style={{margin:0,fontSize:"12px",color:T.txt2,lineHeight:1.6}}>{data.timing}</p></MCard>}
            </div>
          )}
          <GBtn T={T} onClick={()=>setData(null)}>↩ Caută alta strategie</GBtn>
        </div>
      )}
    </div>
  );
}

// ═════════════════════════════════════════════════════════════════════════════
// HOOK ANALYZER
// ═════════════════════════════════════════════════════════════════════════════
function HookTab({ T, brand }) {
  const [hook,     setHook]     = useState("");
  const [platform, setPlatform] = useState(brand?.platform||"");
  const [bizType,  setBizType]  = useState(brand?.bizType||"");
  const [loading,  setLoading]  = useState(false);
  const [result,   setResult]   = useState(null);
  const [err,      setErr]      = useState("");
  const [history,  setHistory]  = useState(() => LS.get("vc_hooks", []));
  const [showHist, setShowHist] = useState(false);

  useEffect(() => { LS.set("vc_hooks", history.slice(0, 20)); }, [history]);

  const canAnalyze = hook.trim().length >= 5 && platform;

  const SCORE_LABELS = [
    { key:"claritate",    label:"Claritate",      color:"#6366f1" },
    { key:"curiozitate",  label:"Curiozitate",    color:"#f472b6" },
    { key:"urgenta",      label:"Urgenta / FOMO", color:"#f87171" },
    { key:"specificitate",label:"Specificitate",  color:"#2dd4bf" },
    { key:"emotional",    label:"Impact emotional",color:"#fbbf24" },
  ];

  async function analyze() {
    setLoading(true); setErr(""); setResult(null);
    const dc = getDateContext();
    const prompt =
      "Ești expert în hook-uri virale pentru social media România, " + dc.complet + ".\n" +
      "Hook: \"" + hook + "\"\n" +
      "Platforma: " + platform + (bizType ? "\nAfacere: " + bizType : "") + "\n\n" +
      "Returnează EXCLUSIV un obiect JSON valid, fără text înainte sau după:\n" +
      "{" +
      "\"nota_generala\":7," +
      "\"claritate\":7,\"claritate_motiv\":\"explicatie scurta\"," +
      "\"curiozitate\":8,\"curiozitate_motiv\":\"explicatie scurta\"," +
      "\"urgenta\":6,\"urgenta_motiv\":\"explicatie scurta\"," +
      "\"specificitate\":7,\"specificitate_motiv\":\"explicatie scurta\"," +
      "\"emotional\":8,\"emotional_motiv\":\"explicatie scurta\"," +
      "\"puncte_forte\":\"ce functioneaza\"," +
      "\"puncte_slabe\":\"ce trebuie imbunatatit\"," +
      "\"v1\":\"prima varianta imbunatatita\"," +
      "\"v1_stil\":\"de ce e mai buna\"," +
      "\"v2\":\"a doua varianta imbunatatita\"," +
      "\"v2_stil\":\"de ce e mai buna\"," +
      "\"v3\":\"a treia varianta imbunatatita\"," +
      "\"v3_stil\":\"de ce e mai buna\"," +
      "\"sfat_final\":\"sfat principal pentru " + platform + "\"" +
      "}";

    try {
      const r = await callAI(prompt);
      if (!r.nota_generala || !r.v1) throw new Error("Raspuns incomplet. Încearcă din nou.");
      setResult(r);
      setHistory(h => [{
        id: Date.now(),
        hook,
        platform,
        bizType,
        nota: r.nota_generala,
        v1: r.v1,
        date: new Date().toLocaleDateString("ro-RO"),
      }, ...h].slice(0, 20));
    } catch(e) {
      setErr(e.message || "Eroare. Încearcă din nou.");
    } finally {
      setLoading(false);
    }
  }

  const notaColor = (n) => n >= 8 ? T.green : n >= 6 ? T.gold : T.red;

  if (loading) return <Dots label="Analizez hook-ul tau..." T={T}/>;

  return (
    <div style={{ animation:"vcpop 0.3s ease" }}>

      {/* FORM */}
      {!result ? (
        <div style={{ display:"flex", flexDirection:"column", gap:"18px" }}>

          {/* Hook input */}
          <div style={{ background:`linear-gradient(135deg,${T.acc}12,${T.pink}08)`, border:`1px solid ${T.acc}25`, borderRadius:"16px", padding:"16px" }}>
            <Lbl color={T.acc}>Hook-ul tau</Lbl>
            <MTextarea
              value={hook}
              onChange={e => setHook(e.target.value)}
              placeholder={"ex: \"Nu stiam ca pot slabi 10 kg fara sa renunt la pizza\"\nSau: \"Cel mai mare secret al salonului din Cluj...\"\nSau: \"POV: ai o burgerie si nimeni nu stie de tine\""}
              rows={4}
              T={T}
            />
            <div style={{ display:"flex", justifyContent:"space-between", alignItems:"center", marginTop:"8px" }}>
              <p style={{ margin:0, fontSize:"11px", color:T.muted }}>
                Minim 5 caractere
              </p>
              <span style={{ fontSize:"12px", color: hook.length > 100 ? T.red : T.muted }}>
                {hook.length} / 150
              </span>
            </div>
          </div>

          {/* Platform */}
          <div>
            <Lbl color={T.muted}>Platforma țintă</Lbl>
            <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:"8px" }}>
              {PLATFORMS.map(p => (
                <button key={p} onClick={() => setPlatform(p)} style={{
                  padding:"12px", borderRadius:"12px", minHeight:"56px",
                  border:`1.5px solid ${platform===p ? T.teal : T.bord}`,
                  background: platform===p ? `${T.teal}12` : T.faint,
                  color: platform===p ? T.teal : T.txt2,
                  fontSize:"12px", fontWeight: platform===p ? 600 : 400,
                  cursor:"pointer", fontFamily:"inherit",
                }}>{p}</button>
              ))}
            </div>
          </div>

          {/* Biz type optional */}
          <div>
            <Lbl color={T.muted}>Tipul afacerii (optional — pentru context)</Lbl>
            <BizSearch value={bizType} onChange={setBizType} T={T}/>
          </div>

          {err && <ErrBox T={T} msg={err} retry={analyze}/>}

          <PBtn T={T} onClick={analyze} disabled={!canAnalyze} full>
            🎯 Analizează si Imbunatateste Hook-ul
          </PBtn>

          {/* History */}
          {history.length > 0 && (
            <div>
              <button onClick={() => setShowHist(s=>!s)} style={{
                width:"100%", padding:"12px 16px", borderRadius:"12px",
                border:`1px solid ${T.bord}`, background:"transparent",
                color:T.muted, fontSize:"13px", cursor:"pointer",
                fontFamily:"inherit", textAlign:"left", minHeight:"56px",
                display:"flex", justifyContent:"space-between", alignItems:"center",
              }}>
                <span>📋 Hook-uri analizate anterior ({history.length})</span>
                <span>{showHist ? "▲" : "▼"}</span>
              </button>
              {showHist && (
                <div style={{ marginTop:"8px", display:"flex", flexDirection:"column", gap:"8px" }}>
                  {history.map(item => (
                    <div key={item.id} style={{
                      background:T.card, border:`1px solid ${T.bord}`,
                      borderLeft:`4px solid ${notaColor(item.nota)}`,
                      borderRadius:"12px", padding:"12px 14px",
                      cursor:"pointer",
                    }} onClick={() => { setHook(item.hook); setPlatform(item.platform); setBizType(item.bizType||""); }}>
                      <div style={{ display:"flex", justifyContent:"space-between", alignItems:"center", marginBottom:"6px" }}>
                        <span style={{ fontSize:"20px", fontWeight:800, color:notaColor(item.nota) }}>{item.nota}/10</span>
                        <span style={{ fontSize:"11px", color:T.muted }}>{item.platform} · {item.date}</span>
                      </div>
                      <p style={{ margin:0, fontSize:"13px", color:T.txt2, fontStyle:"italic", lineHeight:1.4 }}>"{item.hook}"</p>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}
        </div>

      ) : (
        /* RESULT */
        <div style={{ display:"flex", flexDirection:"column", gap:"12px" }}>

          {/* Header */}
          <div style={{ display:"flex", justifyContent:"space-between", alignItems:"flex-start" }}>
            <div>
              <h2 style={{ margin:0, fontSize:"18px", fontWeight:800 }}>Analiza Hook</h2>
              <p style={{ margin:"4px 0 0", color:T.muted, fontSize:"12px" }}>{platform} {bizType ? "· " + bizType : ""}</p>
            </div>
            <GBtn T={T} sm onClick={() => setResult(null)}>↩ Nou</GBtn>
          </div>

          {/* Hook original */}
          <div style={{ background:T.faint, border:`1px solid ${T.bord}`, borderRadius:"14px", padding:"14px 16px" }}>
            <Lbl color={T.muted}>Hook-ul tau original</Lbl>
            <p style={{ margin:0, fontSize:"15px", fontStyle:"italic", color:T.txt2, lineHeight:1.4 }}>"{hook}"</p>
          </div>

          {/* Nota generala */}
          <div style={{
            background: `linear-gradient(135deg,${notaColor(result.nota_generala)}18,${notaColor(result.nota_generala)}08)`,
            border:`1px solid ${notaColor(result.nota_generala)}40`,
            borderRadius:"16px", padding:"18px", textAlign:"center",
          }}>
            <div style={{ fontSize:"54px", fontWeight:800, color:notaColor(result.nota_generala), lineHeight:1 }}>
              {result.nota_generala}
            </div>
            <div style={{ fontSize:"13px", color:T.muted, marginTop:"4px" }}>/ 10 — scor general</div>
          </div>

          {/* Scoruri detaliate */}
          <div style={{ background:T.card, border:`1px solid ${T.bord}`, borderRadius:"16px", padding:"16px" }}>
            <Lbl color={T.muted}>Analiza detaliata</Lbl>
            <div style={{ display:"flex", flexDirection:"column", gap:"14px" }}>
              {SCORE_LABELS.map(sl => {
                const nota = result[sl.key];
                const motiv = result[sl.key + "_motiv"];
                return (
                  <div key={sl.key}>
                    <div style={{ display:"flex", justifyContent:"space-between", marginBottom:"5px" }}>
                      <span style={{ fontSize:"13px", fontWeight:600, color:T.txt }}>{sl.label}</span>
                      <span style={{ fontSize:"14px", fontWeight:800, color:sl.color }}>{nota}/10</span>
                    </div>
                    <div style={{ height:"6px", background:T.faint, borderRadius:"3px", overflow:"hidden", marginBottom:"6px" }}>
                      <div style={{ height:"100%", width:`${nota*10}%`, background:sl.color, borderRadius:"3px", transition:"width 0.5s" }}/>
                    </div>
                    {motiv && (
                      <p style={{ margin:0, fontSize:"12px", color:T.txt2, lineHeight:1.5 }}>{motiv}</p>
                    )}
                  </div>
                );
              })}
            </div>
          </div>

          {/* Puncte forte / slabe */}
          <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:"10px" }}>
            <div style={{ background:T.card, border:`1px solid ${T.bord}`, borderLeft:`4px solid ${T.green}`, borderRadius:"14px", padding:"14px" }}>
              <Lbl color={T.green}>Puncte forte</Lbl>
              <p style={{ margin:0, fontSize:"12px", color:T.txt2, lineHeight:1.55 }}>{result.puncte_forte}</p>
            </div>
            <div style={{ background:T.card, border:`1px solid ${T.bord}`, borderLeft:`4px solid ${T.red}`, borderRadius:"14px", padding:"14px" }}>
              <Lbl color={T.red}>De imbunatatit</Lbl>
              <p style={{ margin:0, fontSize:"12px", color:T.txt2, lineHeight:1.55 }}>{result.puncte_slabe}</p>
            </div>
          </div>

          {/* Versiuni imbunatatite */}
          <div style={{ background:T.card, border:`1px solid ${T.bord}`, borderRadius:"16px", overflow:"hidden" }}>
            <div style={{ padding:"12px 16px", borderBottom:`1px solid ${T.bord}`, background:`${T.acc}08` }}>
              <Lbl color={T.acc}>3 Versiuni Imbunatatite</Lbl>
            </div>
            <div style={{ padding:"16px", display:"flex", flexDirection:"column", gap:"14px" }}>
              {[
                { v: result.v1, stil: result.v1_stil, num:"01", color: T.acc },
                { v: result.v2, stil: result.v2_stil, num:"02", color: T.pink },
                { v: result.v3, stil: result.v3_stil, num:"03", color: T.teal },
              ].map((item, i) => (
                <div key={i} style={{ borderLeft:`3px solid ${item.color}`, paddingLeft:"14px" }}>
                  <div style={{ display:"flex", justifyContent:"space-between", alignItems:"flex-start", marginBottom:"6px" }}>
                    <span style={{ fontSize:"10px", fontWeight:800, color:item.color, letterSpacing:"2px" }}>VARIANTA {item.num}</span>
                    <button onClick={() => navigator.clipboard.writeText(item.v)} style={{
                      padding:"3px 9px", borderRadius:"8px",
                      border:`1px solid ${T.bord}`, background:"transparent",
                      color:T.muted, fontSize:"10px", cursor:"pointer", fontFamily:"inherit",
                    }}>📋 Copy</button>
                  </div>
                  <p style={{ margin:"0 0 6px", fontSize:"15px", fontWeight:700, color:T.txt, lineHeight:1.3 }}>
                    "{item.v}"
                  </p>
                  <p style={{ margin:0, fontSize:"11px", color:T.muted, lineHeight:1.4 }}>{item.stil}</p>
                </div>
              ))}
            </div>
          </div>

          {/* Sfat final */}
          <div style={{ background:`${T.gold}10`, border:`1px solid ${T.gold}30`, borderRadius:"14px", padding:"14px 16px" }}>
            <Lbl color={T.gold}>Sfatul principal</Lbl>
            <p style={{ margin:0, fontSize:"15px", color:T.txt2, lineHeight:1.7 }}>💡 {result.sfat_final}</p>
          </div>

          {/* Analizează alt hook */}
          <PBtn T={T} onClick={() => { setResult(null); setHook(""); }} full>
            🎯 Analizează alt hook
          </PBtn>
        </div>
      )}
    </div>
  );
}

// ═════════════════════════════════════════════════════════════════════════════
// VIDEO ANALYZER
// ═════════════════════════════════════════════════════════════════════════════
function VideoTab({ T, brand }) {
  const [platform, setPlatform] = useState(brand?.platform||"");
  const [bizType,  setBizType]  = useState(brand?.bizType||"");
  const [hook,     setHook]     = useState("");
  const [script,   setScript]   = useState("");
  const [caption,  setCaption]  = useState("");
  const [extra,    setExtra]    = useState("");
  const [loading,  setLoading]  = useState(false);
  const [result,   setResult]   = useState(null);
  const [err,      setErr]      = useState("");

  const canAnalyze = platform && (hook.trim() || script.trim());

  const CRITERIA = [
    { key:"hook_score",       label:"Hook",           color:"#6366f1" },
    { key:"retentie",         label:"Retentie",       color:"#2dd4bf" },
    { key:"cta_score",        label:"CTA",            color:"#f472b6" },
    { key:"caption_score",    label:"Caption",        color:"#fbbf24" },
    { key:"viral_potential",  label:"Potential viral",color:"#34d399" },
  ];

  async function analyze() {
    setLoading(true); setErr(""); setResult(null);
    const dc = getDateContext();
    const prompt =
      "Analist video social media Romania, " + dc.complet + ". " +
      "Platforma: " + platform +
      (bizType ? ", afacere: " + bizType : "") + ".\n" +
      (hook    ? "Hook: \"" + hook + "\"\n"       : "") +
      (script  ? "Script: \"" + script.slice(0,300) + "\"\n" : "") +
      (caption ? "Caption: \"" + caption.slice(0,150) + "\"\n" : "") +
      (extra   ? "Extra: " + extra + "\n" : "") +
      "Returnează EXCLUSIV un obiect JSON valid, fără text înainte sau după:\n" +
      "{" +
      "\"nota_generala\":8," +
      "\"hook_score\":7,\"hook_obs\":\"observatie scurta\"," +
      "\"retentie\":7,\"retentie_obs\":\"observatie scurta\"," +
      "\"cta_score\":8,\"cta_obs\":\"observatie scurta\"," +
      "\"caption_score\":6,\"caption_obs\":\"observatie scurta\"," +
      "\"viral_potential\":8,\"viral_obs\":\"observatie scurta\"," +
      "\"cel_mai_bun\":\"ce functioneaza bine\"," +
      "\"schimba\":\"ce schimbi urgent\"," +
      "\"hook_nou\":\"hook imbunatatit\"," +
      "\"caption_nou\":\"caption imbunatatit cu hashtag-uri " + dc.an + "\"," +
      "\"sfat1\":\"sfat practic 1\"," +
      "\"sfat2\":\"sfat practic 2\"," +
      "\"sfat3\":\"sfat practic 3\"" +
      "}";

    try {
      const r = await callAI(prompt);
      if (!r.nota_generala) throw new Error("Raspuns incomplet. Încearcă din nou.");
      setResult(r);
    } catch(e) {
      setErr(e.message || "Eroare. Încearcă din nou.");
    } finally {
      setLoading(false);
    }
  }

  const notaColor = (n) => n >= 8 ? T.green : n >= 6 ? T.gold : T.red;

  if (loading) return <Dots label="Analizez videoclipul..." T={T}/>;

  return (
    <div style={{ animation:"vcpop 0.3s ease" }}>

      {!result ? (
        <div style={{ display:"flex", flexDirection:"column", gap:"18px" }}>

          {/* Platforma */}
          <div>
            <Lbl color={T.muted}>Platforma</Lbl>
            <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:"8px" }}>
              {PLATFORMS.map(p => (
                <button key={p} onClick={() => setPlatform(p)} style={{
                  padding:"12px", borderRadius:"12px", minHeight:"56px",
                  border:`1.5px solid ${platform===p ? T.teal : T.bord}`,
                  background: platform===p ? `${T.teal}12` : T.faint,
                  color: platform===p ? T.teal : T.txt2,
                  fontSize:"12px", fontWeight: platform===p ? 600 : 400,
                  cursor:"pointer", fontFamily:"inherit",
                }}>{p}</button>
              ))}
            </div>
          </div>

          {/* Tip afacere */}
          <div>
            <Lbl color={T.muted}>Tipul afacerii (optional)</Lbl>
            <BizSearch value={bizType} onChange={setBizType} T={T}/>
          </div>

          {/* Hook */}
          <div style={{ background:`linear-gradient(135deg,${T.acc}12,${T.pink}08)`, border:`1px solid ${T.acc}25`, borderRadius:"16px", padding:"16px" }}>
            <Lbl color={T.acc}>Hook-ul videoclipului</Lbl>
            <MTextarea value={hook} onChange={e=>setHook(e.target.value)}
              placeholder="Prima fraza sau primele 3 secunde ale videoclipului..." rows={2} T={T}/>
          </div>

          {/* Script */}
          <div>
            <Lbl color={T.muted}>Scriptul / Textul videoclipului (optional)</Lbl>
            <MTextarea value={script} onChange={e=>setScript(e.target.value)}
              placeholder="Copiază sau scrie ce spui in videoclip..." rows={4} T={T}/>
          </div>

          {/* Caption */}
          <div>
            <Lbl color={T.muted}>Caption + Hashtag-uri (optional)</Lbl>
            <MTextarea value={caption} onChange={e=>setCaption(e.target.value)}
              placeholder="Caption-ul de sub videoclip..." rows={2} T={T}/>
          </div>

          {/* Extra */}
          <div>
            <Lbl color={T.muted}>Alte detalii (optional)</Lbl>
            <MInput value={extra} onChange={e=>setExtra(e.target.value)}
              placeholder="ex: 500 vizualizari, 2% engagement, burgerie Cluj..." T={T}/>
          </div>

          {err && <ErrBox T={T} msg={err} retry={analyze}/>}

          <PBtn T={T} onClick={analyze} disabled={!canAnalyze} full>
            🎬 Analizează Videoclipul
          </PBtn>
        </div>

      ) : (
        <div style={{ display:"flex", flexDirection:"column", gap:"12px" }}>

          {/* Header */}
          <div style={{ display:"flex", justifyContent:"space-between", alignItems:"center" }}>
            <div>
              <h2 style={{ margin:0, fontSize:"18px", fontWeight:800 }}>Analiza Video</h2>
              <p style={{ margin:"4px 0 0", color:T.muted, fontSize:"12px" }}>{platform}{bizType ? " · " + bizType : ""}</p>
            </div>
            <GBtn T={T} sm onClick={() => setResult(null)}>↩ Nou</GBtn>
          </div>

          {/* Nota generala */}
          <div style={{
            background:`linear-gradient(135deg,${notaColor(result.nota_generala)}18,${notaColor(result.nota_generala)}06)`,
            border:`1px solid ${notaColor(result.nota_generala)}40`,
            borderRadius:"16px", padding:"20px", textAlign:"center",
          }}>
            <div style={{ fontSize:"56px", fontWeight:800, color:notaColor(result.nota_generala), lineHeight:1 }}>
              {result.nota_generala}
            </div>
            <div style={{ fontSize:"13px", color:T.muted, marginTop:"4px" }}>/ 10 — scor general videoclip</div>
          </div>

          {/* Scoruri */}
          <MCard T={T} accent={T.acc} label="Scoruri detaliate">
            <div style={{ display:"flex", flexDirection:"column", gap:"14px" }}>
              {CRITERIA.map(cr => {
                const nota = result[cr.key];
                const obs  = result[cr.key.replace("_score","").replace("viral_potential","viral") + "_obs"] ||
                             result[cr.key + "_obs"] ||
                             result["viral_obs"];
                return (
                  <div key={cr.key}>
                    <div style={{ display:"flex", justifyContent:"space-between", marginBottom:"5px" }}>
                      <span style={{ fontSize:"13px", fontWeight:600, color:T.txt }}>{cr.label}</span>
                      <span style={{ fontSize:"14px", fontWeight:800, color:cr.color }}>{nota}/10</span>
                    </div>
                    <div style={{ height:"6px", background:T.faint, borderRadius:"3px", overflow:"hidden", marginBottom:"5px" }}>
                      <div style={{ height:"100%", width:`${(nota||0)*10}%`, background:cr.color, borderRadius:"3px" }}/>
                    </div>
                    {obs && <p style={{ margin:0, fontSize:"12px", color:T.txt2 }}>{obs}</p>}
                  </div>
                );
              })}
            </div>
          </MCard>

          {/* Cel mai bun / Schimbă */}
          <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:"10px" }}>
            <div style={{ background:T.card, border:`1px solid ${T.bord}`, borderLeft:`4px solid ${T.green}`, borderRadius:"14px", padding:"14px" }}>
              <Lbl color={T.green}>Cel mai bun</Lbl>
              <p style={{ margin:0, fontSize:"12px", color:T.txt2, lineHeight:1.5 }}>{result.cel_mai_bun}</p>
            </div>
            <div style={{ background:T.card, border:`1px solid ${T.bord}`, borderLeft:`4px solid ${T.red}`, borderRadius:"14px", padding:"14px" }}>
              <Lbl color={T.red}>Schimbă urgent</Lbl>
              <p style={{ margin:0, fontSize:"12px", color:T.txt2, lineHeight:1.5 }}>{result.schimba}</p>
            </div>
          </div>

          {/* Hook nou */}
          {result.hook_nou && (
            <div style={{ background:T.card, border:`1px solid ${T.bord}`, borderLeft:`4px solid ${T.acc}`, borderRadius:"14px", padding:"14px" }}>
              <div style={{ display:"flex", justifyContent:"space-between", alignItems:"center", marginBottom:"8px" }}>
                <Lbl color={T.acc}>Hook imbunatatit</Lbl>
                <button onClick={() => navigator.clipboard.writeText(result.hook_nou)} style={{ padding:"4px 10px", borderRadius:"8px", border:`1px solid ${T.bord}`, background:"transparent", color:T.muted, fontSize:"11px", cursor:"pointer", fontFamily:"inherit" }}>📋 Copy</button>
              </div>
              <p style={{ margin:0, fontSize:"15px", fontWeight:700, color:T.txt, fontStyle:"italic", lineHeight:1.3 }}>"{result.hook_nou}"</p>
            </div>
          )}

          {/* Caption nou */}
          {result.caption_nou && (
            <div style={{ background:T.card, border:`1px solid ${T.bord}`, borderLeft:`4px solid ${T.pink}`, borderRadius:"14px", padding:"14px" }}>
              <div style={{ display:"flex", justifyContent:"space-between", alignItems:"center", marginBottom:"8px" }}>
                <Lbl color={T.pink}>Caption imbunatatit</Lbl>
                <button onClick={() => navigator.clipboard.writeText(result.caption_nou)} style={{ padding:"4px 10px", borderRadius:"8px", border:`1px solid ${T.bord}`, background:"transparent", color:T.muted, fontSize:"11px", cursor:"pointer", fontFamily:"inherit" }}>📋 Copy</button>
              </div>
              <p style={{ margin:0, fontSize:"15px", color:T.txt2, lineHeight:1.7 }}>{result.caption_nou}</p>
            </div>
          )}

          {/* 3 sfaturi */}
          {(result.sfat1 || result.sfat2 || result.sfat3) && (
            <MCard T={T} accent={T.gold} label="3 Sfaturi practice">
              {[result.sfat1, result.sfat2, result.sfat3].filter(Boolean).map((s, i) => (
                <div key={i} style={{ display:"flex", gap:"12px", marginBottom:"10px" }}>
                  <span style={{ background:T.gold, color:"#000", borderRadius:"50%", width:"22px", height:"22px", display:"flex", alignItems:"center", justifyContent:"center", fontSize:"11px", fontWeight:800, flexShrink:0 }}>{i+1}</span>
                  <p style={{ margin:0, fontSize:"15px", color:T.txt2, lineHeight:1.7 }}>{s}</p>
                </div>
              ))}
            </MCard>
          )}

          <PBtn T={T} onClick={() => { setResult(null); setHook(""); setScript(""); setCaption(""); setExtra(""); }} full>
            🎬 Analizează alt videoclip
          </PBtn>
        </div>
      )}
    </div>
  );
}

// ═════════════════════════════════════════════════════════════════════════════
// PROFIL TAB — brand profile salvat
// ═════════════════════════════════════════════════════════════════════════════
function ProfilTab({ T, brand, updateBrand, dark, setDark, accent, setAccent, history, setHistory, totalScripts, stats, bottomTabs, setBottomTabs }) {
  const [saved, setSaved] = useState(false);

  // Auto-save la fiecare schimbare de profil
  useEffect(() => {
    if (!brand.bizName && !brand.bizType) return;
    setSaved(true);
    const t = setTimeout(() => setSaved(false), 2000);
    return () => clearTimeout(t);
  }, [brand.bizName, brand.bizType, brand.platform, brand.tone, brand.city, brand.about]);

  const filled = [brand.bizName, brand.bizType, brand.platform, brand.tone].filter(Boolean).length;
  const pct = Math.round((filled / 4) * 100);

  return (
    <div style={{ display:"flex", flexDirection:"column", gap:"18px", animation:"vcpop 0.3s ease" }}>

      {/* Header card */}
      <div style={{
        background:`linear-gradient(135deg,${T.acc}18,${T.pink}10)`,
        border:`1px solid ${T.acc}25`,
        borderRadius:"20px", padding:"20px",
      }}>
        <div style={{ display:"flex", alignItems:"center", gap:"14px", marginBottom:"16px" }}>
          <div style={{
            width:"56px", height:"56px", borderRadius:"16px",
            background:`linear-gradient(135deg,${T.acc},${T.pink})`,
            display:"flex", alignItems:"center", justifyContent:"center",
            fontSize:"24px", flexShrink:0,
            boxShadow:`0 6px 20px ${T.acc}40`,
          }}>
            {brand.bizName ? brand.bizName.charAt(0).toUpperCase() : "🏢"}
          </div>
          <div style={{ flex:1 }}>
            <div style={{ fontSize:"18px", fontWeight:800, color:T.txt, lineHeight:1 }}>
              {brand.bizName || "Afacerea ta"}
            </div>
            <div style={{ fontSize:"12px", color:T.muted, marginTop:"4px" }}>
              {brand.bizType || "Tip nesetat"} {brand.city ? "· " + brand.city : ""}
            </div>
          </div>
        </div>

        {/* Stats */}
        <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:"10px", marginTop:"14px", marginBottom:"14px" }}>
          <div style={{ background:`${T.acc}12`, border:`1px solid ${T.acc}25`, borderRadius:"14px", padding:"14px", textAlign:"center" }}>
            <div style={{ fontSize:"28px", fontWeight:800, color:T.acc }}>{totalScripts||0}</div>
            <div style={{ fontSize:"11px", color:T.muted, marginTop:"3px" }}>generări totale</div>
          </div>
          <div style={{ background:`${T.gold}12`, border:`1px solid ${T.gold}25`, borderRadius:"14px", padding:"14px", textAlign:"center" }}>
            <div style={{ fontSize:"28px", fontWeight:800, color:T.gold }}>{history.filter(x=>!x.type||x.type==="script").length}</div>
            <div style={{ fontSize:"11px", color:T.muted, marginTop:"3px" }}>scripturi video</div>
          </div>
        </div>

        {/* Completare profil */}
        <div>
          <div style={{ display:"flex", justifyContent:"space-between", marginBottom:"6px" }}>
            <span style={{ fontSize:"11px", color:T.acc, fontWeight:600 }}>Profil completat</span>
            <span style={{ fontSize:"11px", color:T.acc, fontWeight:800 }}>{pct}%</span>
          </div>
          <div style={{ height:"5px", background:T.bord, borderRadius:"3px", overflow:"hidden" }}>
            <div style={{ height:"100%", width:`${pct}%`, background:`linear-gradient(90deg,${T.acc},${T.pink})`, borderRadius:"3px", transition:"width 0.5s" }}/>
          </div>
          {pct < 100 && <p style={{ margin:"6px 0 0", fontSize:"11px", color:T.muted }}>Completează profilul pentru generări mai precise</p>}
        </div>
      </div>

      {/* Informatii afacere */}
      <div style={{ background:T.card, border:`1px solid ${T.bord}`, borderRadius:"18px", overflow:"hidden", boxShadow:`0 4px 24px ${T.shadow}` }}>
        <div style={{ padding:"14px 18px", borderBottom:`1px solid ${T.bord}`, background:`${T.acc}08` }}>
          <div style={{ fontSize:"10px", fontWeight:700, letterSpacing:"2px", color:T.acc, textTransform:"uppercase" }}>Informatii afacere</div>
        </div>
        <div style={{ padding:"18px", display:"flex", flexDirection:"column", gap:"14px" }}>
          <div>
            <div style={{ fontSize:"14px", fontWeight:800, color:T.txt, marginBottom:"8px" }}>Numele afacerii</div>
            <MInput value={brand.bizName} onChange={e=>updateBrand("bizName",e.target.value)}
              placeholder="Numele afacerii tale" T={T} big/>
          </div>
          <div>
            <div style={{ fontSize:"14px", fontWeight:800, color:T.txt, marginBottom:"8px" }}>Tipul afacerii</div>
            <BizSearch value={brand.bizType} onChange={v=>updateBrand("bizType",v)} T={T}/>
          </div>
          <div>
            <div style={{ fontSize:"14px", fontWeight:800, color:T.txt, marginBottom:"8px" }}>Orasul / Zona</div>
            <CitySearch value={brand.city||""} onChange={v=>updateBrand("city",v)} T={T}/>
          </div>
          <div>
            <div style={{ fontSize:"14px", fontWeight:800, color:T.txt, marginBottom:"8px" }}>Despre afacere (optional)</div>
            <MTextarea value={brand.about||""} onChange={e=>updateBrand("about",e.target.value)}
              placeholder="ex: restaurantul nostru e cunoscut pentru burgerii artizanali si atmosfera relaxata..." T={T} rows={3}/>
          </div>
        </div>
      </div>

      {/* Preferinte implicite */}
      <div style={{ background:T.card, border:`1px solid ${T.bord}`, borderRadius:"18px", overflow:"hidden", boxShadow:`0 4px 24px ${T.shadow}` }}>
        <div style={{ padding:"14px 18px", borderBottom:`1px solid ${T.bord}`, background:`${T.teal}08` }}>
          <div style={{ fontSize:"10px", fontWeight:700, letterSpacing:"2px", color:T.teal, textTransform:"uppercase" }}>Preferinte implicite</div>
        </div>
        <div style={{ padding:"18px", display:"flex", flexDirection:"column", gap:"14px" }}>
          <div>
            <div style={{ fontSize:"14px", fontWeight:800, color:T.txt, marginBottom:"8px" }}>Platforma preferata</div>
            <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:"8px" }}>
              {PLATFORMS.map(p=>(
                <button key={p} onClick={()=>updateBrand("platform",p)} style={{
                  padding:"10px 12px", borderRadius:"12px", minHeight:"52px",
                  border:`1.5px solid ${brand.platform===p?T.teal:T.bord}`,
                  background:brand.platform===p?`${T.teal}12`:T.faint,
                  color:brand.platform===p?T.teal:T.txt2,
                  fontSize:"12px", fontWeight:brand.platform===p?700:400,
                  cursor:"pointer", fontFamily:"inherit",
                }}>{p}</button>
              ))}
            </div>
          </div>
          <div>
            <div style={{ fontSize:"14px", fontWeight:800, color:T.txt, marginBottom:"8px" }}>Ton preferat</div>
            <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr 1fr", gap:"8px" }}>
              {TONES.map(t=>(
                <button key={t} onClick={()=>updateBrand("tone",t)} style={{
                  padding:"10px 8px", borderRadius:"12px", minHeight:"52px",
                  border:`1.5px solid ${brand.tone===t?T.pink:T.bord}`,
                  background:brand.tone===t?`${T.pink}12`:T.faint,
                  color:brand.tone===t?T.pink:T.txt2,
                  fontSize:"11px", fontWeight:brand.tone===t?700:400,
                  cursor:"pointer", fontFamily:"inherit",
                }}>{t}</button>
              ))}
            </div>
          </div>
        </div>
      </div>

      {/* Auto-save indicator */}
      <div style={{
        padding:"14px 18px", borderRadius:"14px",
        background: saved ? `${T.green}12` : T.faint,
        border: `1px solid ${saved ? T.green+"40" : T.bord}`,
        display:"flex", alignItems:"center", gap:"10px",
        transition:"all 0.3s",
      }}>
        <span style={{fontSize:"18px"}}>{saved ? "✅" : "💾"}</span>
        <div>
          <div style={{fontSize:"14px", fontWeight:700, color: saved ? T.green : T.txt2}}>
            {saved ? "Profil salvat automat!" : "Profilul se salvează automat"}
          </div>
          <div style={{fontSize:"12px", color:T.muted}}>
            {saved ? "Toate tab-urile sunt actualizate" : "Orice modificare e salvată instant"}
          </div>
        </div>
      </div>

      {/* Setari */}
      <div style={{ background:T.card, border:`1px solid ${T.bord}`, borderRadius:"18px", overflow:"hidden", boxShadow:`0 4px 24px ${T.shadow}` }}>
        <div style={{ padding:"14px 18px", borderBottom:`1px solid ${T.bord}` }}>
          <div style={{ fontSize:"10px", fontWeight:700, letterSpacing:"2px", color:T.muted, textTransform:"uppercase" }}>Setari</div>
        </div>
        <div style={{ padding:"8px" }}>

          {/* Accent color picker */}
          <div style={{ display:"flex", justifyContent:"space-between", alignItems:"center", padding:"12px 10px", borderRadius:"12px", borderBottom:`1px solid ${T.bord}` }}>
            <div style={{ display:"flex", alignItems:"center", gap:"12px" }}>
              <span style={{ fontSize:"20px" }}>🎨</span>
              <div>
                <div style={{ fontSize:"14px", fontWeight:600, color:T.txt }}>Culoarea accentului</div>
                <div style={{ fontSize:"11px", color:T.muted }}>Personalizeaza culorile aplicatiei</div>
              </div>
            </div>
            <div style={{ display:"flex", gap:"8px" }}>
              {ACCENTS.map(a=>(
                <button key={a.id} onClick={()=>setAccent(a.id)} style={{
                  width:"26px", height:"26px", borderRadius:"50%",
                  background:dark?a.dark:a.light,
                  border:accent===a.id?`3px solid ${T.txt}`:`3px solid transparent`,
                  cursor:"pointer", padding:0,
                  boxShadow:accent===a.id?`0 0 0 2px ${dark?a.dark:a.light}60`:"none",
                  transition:"all 0.2s",
                }} title={a.label}/>
              ))}
            </div>
          </div>

          {/* Dark mode toggle */}
          <div style={{ display:"flex", justifyContent:"space-between", alignItems:"center", padding:"12px 10px", borderRadius:"12px" }}>
            <div style={{ display:"flex", alignItems:"center", gap:"12px" }}>
              <span style={{ fontSize:"20px" }}>{dark?"🌙":"☀️"}</span>
              <div>
                <div style={{ fontSize:"14px", fontWeight:600, color:T.txt }}>Tema {dark?"intunecata":"luminoasa"}</div>
                <div style={{ fontSize:"11px", color:T.muted }}>Schimbă aspectul aplicatiei</div>
              </div>
            </div>
            <button onClick={()=>setDark(d=>!d)} style={{
              width:"48px", height:"28px", borderRadius:"14px",
              background: dark ? T.acc : T.bord,
              border:"none", cursor:"pointer", position:"relative",
              transition:"background 0.3s",
            }}>
              <div style={{
                width:"22px", height:"22px", borderRadius:"50%",
                background:"#fff",
                position:"absolute", top:"3px",
                left: dark ? "23px" : "3px",
                transition:"left 0.3s",
                boxShadow:"0 2px 6px rgba(0,0,0,0.3)",
              }}/>
            </button>
          </div>

          {/* Șterge istoricul */}
          {history.length > 0 && (
            <button onClick={()=>{ if(window.confirm("Stergi tot istoricul?")) setHistory([]); }} style={{
              width:"100%", padding:"12px 10px", borderRadius:"12px",
              border:"none", background:"transparent",
              display:"flex", alignItems:"center", gap:"12px",
              cursor:"pointer", fontFamily:"inherit",
            }}
              onMouseEnter={e=>e.currentTarget.style.background=`${T.red}10`}
              onMouseLeave={e=>e.currentTarget.style.background="transparent"}>
              <span style={{ fontSize:"20px" }}>🗑</span>
              <div style={{ textAlign:"left" }}>
                <div style={{ fontSize:"14px", fontWeight:600, color:T.red }}>Șterge istoricul</div>
                <div style={{ fontSize:"11px", color:T.muted }}>{history.length} elemente salvate</div>
              </div>
            </button>
          )}
        </div>
      </div>

      {/* Analytics — cele mai folosite funcții */}
      {stats && Object.keys(stats).length > 0 && (
        <div style={{ background:T.card, border:`1px solid ${T.bord}`, borderRadius:"18px", overflow:"hidden", boxShadow:`0 4px 24px ${T.shadow}` }}>
          <div style={{ padding:"14px 18px", borderBottom:`1px solid ${T.bord}`, background:`${T.teal}08` }}>
            <div style={{ fontSize:"10px", fontWeight:700, letterSpacing:"2px", color:T.teal, textTransform:"uppercase" }}>📊 Funcții folosite</div>
          </div>
          <div style={{ padding:"14px 18px" }}>
            {Object.entries(stats)
              .sort((a,b)=>b[1]-a[1])
              .slice(0,6)
              .map(([id,count],i)=>{
                const navItem = NAV.find(n=>n.id===id);
                if(!navItem) return null;
                const max = Math.max(...Object.values(stats));
                const pct = Math.round((count/max)*100);
                return (
                  <div key={id} style={{ marginBottom: i<5?"12px":"0" }}>
                    <div style={{ display:"flex", justifyContent:"space-between", marginBottom:"5px" }}>
                      <span style={{ fontSize:"13px", color:T.txt2 }}>{navItem.icon} {navItem.label}</span>
                      <span style={{ fontSize:"12px", fontWeight:700, color:T.teal }}>{count}x</span>
                    </div>
                    <div style={{ height:"5px", background:T.faint, borderRadius:"3px", overflow:"hidden" }}>
                      <div style={{ height:"100%", width:`${pct}%`, background:`linear-gradient(90deg,${T.teal},${T.acc})`, borderRadius:"3px", transition:"width 0.5s" }}/>
                    </div>
                  </div>
                );
              })}
            <p style={{ margin:"12px 0 0", fontSize:"11px", color:T.muted }}>Bazat pe sesiunile tale în aplicație</p>
          </div>
        </div>
      )}

      {/* Tab-uri personalizate */}
      <div style={{ background:T.card, border:`1px solid ${T.bord}`, borderRadius:"18px", overflow:"hidden", boxShadow:`0 4px 24px ${T.shadow}` }}>
        <div style={{ padding:"14px 18px", borderBottom:`1px solid ${T.bord}`, background:`${T.pink}08` }}>
          <div style={{ fontSize:"10px", fontWeight:700, letterSpacing:"2px", color:T.pink, textTransform:"uppercase" }}>📌 Tab-uri bara de jos</div>
          <div style={{ fontSize:"11px", color:T.muted, marginTop:"3px" }}>Alege maxim 4 tab-uri — apar în ordinea selectată</div>
        </div>

        {/* Preview bara */}
        <div style={{ padding:"12px 18px", borderBottom:`1px solid ${T.bord}`, background:T.faint }}>
          <div style={{ fontSize:"10px", color:T.muted, marginBottom:"8px", fontWeight:600 }}>PREVIZUALIZARE</div>
          <div style={{ display:"flex", gap:"4px" }}>
            {bottomTabs.map((id,i)=>{
              const n = NAV.find(x=>x.id===id);
              if(!n) return null;
              const active = i===0;
              return (
                <div key={id} style={{
                  flex:1, display:"flex", flexDirection:"column", alignItems:"center",
                  gap:"2px", padding:"6px 2px",
                  background:active?`${T.acc}15`:"transparent",
                  borderRadius:"8px",
                  borderTop:active?`2px solid ${T.acc}`:"2px solid transparent",
                }}>
                  <span style={{fontSize:"16px"}}>{n.icon}</span>
                  <span style={{fontSize:"8px",color:active?T.acc:T.muted,fontWeight:active?700:400}}>{n.label}</span>
                </div>
              );
            })}
          </div>
        </div>

        <div style={{ padding:"14px 18px" }}>
          <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:"8px" }}>
            {NAV.filter(n=>n.id!=="profil").map(n=>{
              const selIdx = bottomTabs.filter(t=>t!=="profil").indexOf(n.id);
              const sel = selIdx !== -1;
              const atMax = bottomTabs.filter(t=>t!=="profil").length >= 4;
              return (
                <button key={n.id} onClick={()=>{
                  if(sel) {
                    // Remove — preservă ordinea celorlalte
                    setBottomTabs(t=>t.filter(x=>x!==n.id));
                  } else if(!atMax) {
                    // Adaugă la final, înainte de profil
                    setBottomTabs(t=>[...t.filter(x=>x!=="profil"), n.id, "profil"]);
                  }
                }} style={{
                  padding:"10px 12px",borderRadius:"12px",minHeight:"56px",
                  border:`1.5px solid ${sel?T.pink:T.bord}`,
                  background:sel?`${T.pink}12`:T.faint,
                  color:sel?T.pink:atMax&&!sel?T.muted:T.txt2,
                  fontSize:"12px",fontWeight:sel?700:400,
                  cursor:atMax&&!sel?"not-allowed":"pointer",
                  fontFamily:"inherit",
                  display:"flex",alignItems:"center",gap:"8px",
                  opacity:atMax&&!sel?0.45:1,
                }}>
                  <span style={{fontSize:"18px"}}>{n.icon}</span>
                  <span style={{flex:1,textAlign:"left"}}>{n.label}</span>
                  {sel&&(
                    <span style={{
                      width:"20px",height:"20px",borderRadius:"50%",
                      background:T.pink,color:"#fff",
                      fontSize:"10px",fontWeight:800,
                      display:"flex",alignItems:"center",justifyContent:"center",
                      flexShrink:0,
                    }}>{selIdx+1}</span>
                  )}
                </button>
              );
            })}
          </div>
          <p style={{ margin:"10px 0 0", fontSize:"11px", color:T.muted }}>
            👤 Profil e mereu ultimul · {4-(bottomTabs.filter(t=>t!=="profil").length)} locuri disponibile
          </p>
        </div>
      </div>

      {/* About */}
      <div style={{ textAlign:"center", padding:"8px 0 4px" }}>
        <div style={{ fontSize:"22px", fontWeight:800, letterSpacing:"-1px",
          background:`linear-gradient(135deg,${T.acc},${T.pink})`,
          WebkitBackgroundClip:"text", WebkitTextFillColor:"transparent",
          marginBottom:"4px" }}>creavo</div>
        <div style={{ fontSize:"10px", color:T.muted, letterSpacing:"3px" }}>AI CONTENT · Beta</div>
        <div style={{ fontSize:"11px", color:T.muted, marginTop:"8px" }}>pentru afaceri din Romania</div>
      </div>

    </div>
  );
}

// ═════════════════════════════════════════════════════════════════════════════
// ONBOARDING SCREEN
// ═════════════════════════════════════════════════════════════════════════════
function OnboardingScreen({ T, onDone }) {
  const [slide, setSlide] = useState(0);

  const SLIDES = [
    {
      emoji:"👋",
      title:"Bine ai venit la Creavo!",
      desc:"Aplicația AI care îți scrie scripturi virale pentru TikTok și Instagram în 15 secunde — specifice pentru afacerea ta.",
      color:T.acc,
      tip:null,
    },
    {
      emoji:"1️⃣",
      title:"Completează profilul",
      desc:"Mergi la 👤 Profil și completează numele afacerii, tipul și platforma preferată. 1 minut — și toate generările vor fi personalizate automat.",
      color:T.teal,
      tip:"💡 Fă asta primul — economisești timp la fiecare generare",
    },
    {
      emoji:"2️⃣",
      title:"Generează primul script",
      desc:"La ⚡ Generator, selectează un template și apasă Generează. În 15-20 secunde ai hook, script, caption și hashtag-uri gata de copiat.",
      color:T.pink,
      tip:"💡 Încearcă templateul 'Generic' prima dată",
    },
    {
      emoji:"3️⃣",
      title:"Copiază și filmează",
      desc:"Copiază scriptul cu un tap sau trimite-l direct pe WhatsApp. Ai exact ce să spui în fața camerei — nu mai improvizezi.",
      color:T.gold,
      tip:"💡 Butonul verde 'Trimite pe WhatsApp' e cel mai rapid",
    },
    {
      emoji:"🚀",
      title:"Ești gata de start!",
      desc:"Hai să configurăm profilul tău acum — durează 60 de secunde și Creavo va personaliza tot conținutul pentru afacerea ta.",
      color:T.green,
      tip:null,
    },
  ];

  const s = SLIDES[slide];
  const isLast = slide === SLIDES.length - 1;

  return (
    <div style={{
      minHeight:"100vh", maxWidth:"480px", margin:"0 auto",
      background:T.bg, color:T.txt,
      fontFamily:"'Inter',-apple-system,sans-serif",
      display:"flex", flexDirection:"column",
      alignItems:"center", justifyContent:"space-between",
      padding:"60px 28px 48px",
      position:"relative", overflow:"hidden",
    }}>
      <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet"/>

      {/* Ambient glow */}
      <div style={{
        position:"absolute", top:"-80px", left:"50%", transform:"translateX(-50%)",
        width:"500px", height:"400px",
        background:`radial-gradient(ellipse,${s.color}20 0%,transparent 70%)`,
        pointerEvents:"none", transition:"background 0.5s",
      }}/>

      {/* Skip */}
      <button onClick={onDone} style={{
        position:"absolute", top:"20px", right:"20px",
        padding:"6px 14px", borderRadius:"20px",
        border:`1px solid ${T.bord}`, background:"transparent",
        color:T.muted, fontSize:"12px", cursor:"pointer", fontFamily:"inherit",
      }}>Sari peste</button>

      {slide > 0 && (
        <div style={{position:"absolute",top:"24px",left:"20px",fontSize:"13px",color:T.muted,fontWeight:600}}>
          {slide} / {SLIDES.length - 1}
        </div>
      )}

      {/* Content */}
      <div style={{ flex:1, display:"flex", flexDirection:"column", alignItems:"center", justifyContent:"center", textAlign:"center" }}>

        {/* Emoji icon */}
        <div key={slide} style={{
          width:"96px", height:"96px", borderRadius:"28px",
          background:`linear-gradient(135deg,${s.color}25,${s.color}10)`,
          border:`2px solid ${s.color}35`,
          display:"flex", alignItems:"center", justifyContent:"center",
          fontSize:"46px", marginBottom:"28px",
          boxShadow:`0 16px 48px ${s.color}30`,
          animation:"vcpop 0.35s ease",
        }}>
          {s.emoji}
        </div>

        <h1 style={{
          fontSize:"23px", fontWeight:800, margin:"0 0 12px",
          letterSpacing:"-0.5px", lineHeight:1.2,
          color:s.color,
        }}>{s.title}</h1>

        <p style={{
          fontSize:"15px", color:T.txt2, lineHeight:1.7,
          margin:"0 0 18px", maxWidth:"320px",
        }}>{s.desc}</p>

        {s.tip && (
          <div style={{
            padding:"10px 16px", borderRadius:"12px",
            background:`${s.color}12`, border:`1px solid ${s.color}25`,
            fontSize:"13px", color:s.color, fontWeight:500,
            maxWidth:"300px", lineHeight:1.5,
          }}>{s.tip}</div>
        )}
      </div>

      {/* Dots */}
      <div style={{ display:"flex", gap:"8px", marginBottom:"24px" }}>
        {SLIDES.map((_,i)=>(
          <div key={i} onClick={()=>setSlide(i)} style={{
            height:"6px",
            width: i===slide ? "24px" : "6px",
            borderRadius:"3px",
            background: i===slide ? s.color : T.bord,
            transition:"all 0.3s",
            cursor:"pointer",
          }}/>
        ))}
      </div>

      {/* Button */}
      <button onClick={()=>{ if(isLast) onDone(); else setSlide(s=>s+1); }} style={{
        width:"100%", padding:"16px", borderRadius:"16px", border:"none",
        background:`linear-gradient(135deg,${s.color},${s.color}cc)`,
        color:"#fff", fontSize:"16px", fontWeight:700,
        cursor:"pointer", fontFamily:"inherit",
        boxShadow:`0 6px 28px ${s.color}50`,
        transition:"all 0.3s",
      }}>
        {isLast ? "Configurează profilul →" : "Continuă →"}
      </button>

      <style>{`@keyframes vcpop{from{opacity:0;transform:scale(0.8)}to{opacity:1;transform:scale(1)}}`}</style>
    </div>
  );
}

// ═════════════════════════════════════════════════════════════════════════════
// UPGRADE TAB
// ═════════════════════════════════════════════════════════════════════════════
function UpgradeTab({ T }) {
  const PLANS = [
    {
      id:"free", label:"Free", price:"0", per:"lună",
      color:T.muted, badge:"",
      features:["3 scripturi / lună","1 platformă (TikTok)","Fără istoric salvat","Fără scor viral"],
      disabled:["Calendar editorial","Stories AI","Strategie Creatori","Analizor Hook & Video"],
      cta:"Planul tău actual",
      current:true,
    },
    {
      id:"starter", label:"Starter", price:"29", per:"RON / lună",
      color:T.acc, badge:"Popular",
      features:["30 scripturi / lună","Toate platformele","Toate templateurile","Calendar editorial","Stories AI","Istoric salvat","Scor viral"],
      disabled:["Strategie Creatori","Analizor Video"],
      cta:"Alege Starter",
      current:false,
    },
    {
      id:"pro", label:"Pro", price:"79", per:"RON / lună",
      color:T.pink, badge:"Cel mai bun",
      features:["Scripturi nelimitate","Toate funcțiile","Strategie Creatori","Analizor Hook & Video","Suport WhatsApp","Acces funcții noi primul"],
      disabled:[],
      cta:"Alege Pro",
      current:false,
    },
    {
      id:"agentie", label:"Agenție", price:"199", per:"RON / lună",
      color:T.gold, badge:"",
      features:["Tot din Pro","5 brand-uri separate","Export PDF","White label (fără logo Creavo)","Rapoarte lunare","Factură fiscală"],
      disabled:[],
      cta:"Alege Agenție",
      current:false,
    },
  ];

  return (
    <div style={{ animation:"vcpop 0.3s ease" }}>
      <div style={{ textAlign:"center", marginBottom:"24px" }}>
        <div style={{ fontSize:"32px", marginBottom:"8px" }}>💎</div>
        <h2 style={{ margin:"0 0 6px", fontSize:"22px", fontWeight:800, color:T.txt }}>Alege planul tău</h2>
        <p style={{ margin:0, fontSize:"14px", color:T.muted }}>Fără contract. Anulezi oricând.</p>
      </div>

      <div style={{ display:"flex", flexDirection:"column", gap:"12px" }}>
        {PLANS.map(plan=>(
          <div key={plan.id} style={{
            background:T.card,
            border:`2px solid ${plan.current?T.bord:plan.color+"50"}`,
            borderRadius:"20px", overflow:"hidden",
            boxShadow: plan.current?"none":`0 4px 24px ${plan.color}20`,
          }}>
            <div style={{
              padding:"16px 20px",
              background: plan.current?"transparent":`linear-gradient(135deg,${plan.color}15,${plan.color}05)`,
              display:"flex", justifyContent:"space-between", alignItems:"center",
            }}>
              <div>
                <div style={{ display:"flex", alignItems:"center", gap:"8px", marginBottom:"4px" }}>
                  <span style={{ fontSize:"16px", fontWeight:800, color:plan.current?T.muted:plan.color }}>{plan.label}</span>
                  {plan.badge&&<span style={{ fontSize:"10px", padding:"2px 8px", borderRadius:"20px", background:plan.color, color:"#fff", fontWeight:700 }}>{plan.badge}</span>}
                </div>
                <div style={{ display:"flex", alignItems:"baseline", gap:"4px" }}>
                  <span style={{ fontSize:"26px", fontWeight:800, color:plan.current?T.muted:plan.txt||T.txt }}>{plan.price}</span>
                  <span style={{ fontSize:"12px", color:T.muted }}>{plan.per}</span>
                </div>
              </div>
              <button style={{
                padding:"10px 20px", borderRadius:"12px",
                border: plan.current?`1px solid ${T.bord}`:"none",
                background: plan.current?T.faint:`linear-gradient(135deg,${plan.color},${plan.color}cc)`,
                color: plan.current?T.muted:"#fff",
                fontSize:"13px", fontWeight:700,
                cursor: plan.current?"default":"pointer",
                fontFamily:"inherit", minHeight:"42px",
                boxShadow: plan.current?"none":`0 4px 16px ${plan.color}40`,
              }}>
                {plan.cta}
              </button>
            </div>
            <div style={{ padding:"14px 20px", borderTop:`1px solid ${T.bord}` }}>
              {plan.features.map((f,i)=>(
                <div key={i} style={{ display:"flex", alignItems:"center", gap:"10px", marginBottom:"8px" }}>
                  <span style={{ color:plan.current?T.muted:T.green, fontSize:"14px", flexShrink:0 }}>✓</span>
                  <span style={{ fontSize:"13px", color:T.txt2 }}>{f}</span>
                </div>
              ))}
              {plan.disabled.map((f,i)=>(
                <div key={i} style={{ display:"flex", alignItems:"center", gap:"10px", marginBottom:"8px", opacity:0.4 }}>
                  <span style={{ color:T.muted, fontSize:"14px", flexShrink:0 }}>✕</span>
                  <span style={{ fontSize:"13px", color:T.muted, textDecoration:"line-through" }}>{f}</span>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>

      <div style={{ textAlign:"center", padding:"20px 0 8px" }}>
        <p style={{ fontSize:"12px", color:T.muted, margin:0 }}>Plată securizată · Suport WhatsApp · Factură inclusă</p>
      </div>
    </div>
  );
}

// ═════════════════════════════════════════════════════════════════════════════
// HELP TAB — Cum funcționează
// ═════════════════════════════════════════════════════════════════════════════
function HelpTab({ T }) {
  const [open, setOpen] = useState(null);

  const STEPS = [
    {
      icon:"👤", title:"1. Configurează-ți profilul",
      desc:"Mergi la tab-ul Profil și completează numele afacerii, tipul și platforma preferată. Creavo va folosi aceste date la fiecare generare — nu mai completezi de fiecare dată.",
    },
    {
      icon:"⚡", title:"2. Generează primul script",
      desc:"La Generator, selectează templateul dorit (Generic, Poveste client, POV etc.), alege durata și apasă Generează. În 10-20 secunde primești un script complet cu hook, text și caption.",
    },
    {
      icon:"🎯", title:"3. Analizează-ți hook-urile",
      desc:"La tab-ul Hook, bagă primele 3 secunde ale videoclipului tău și primești o notă din 10 + 3 variante îmbunătățite. Testează variante A/B pentru engagement mai mare.",
    },
    {
      icon:"🔥", title:"4. Urmărește trendurile",
      desc:"Tab-ul Trenduri îți arată ce e viral acum pe TikTok și Instagram în România pentru tipul tău de afacere — cu hook-uri gata de folosit și hashtag-uri actuale.",
    },
    {
      icon:"📅", title:"5. Planifică cu Calendarul",
      desc:"Generează un calendar editorial săptămânal complet — ce postezi, când, pe ce platformă și ce hook folosești. Ideal pentru a fi constant pe social media.",
    },
    {
      icon:"📸", title:"6. Creează Stories perfecte",
      desc:"Tab-ul Stories generează o idee completă de Instagram Story — ce filmezi, textul overlay, tipul stickerului și CTA-ul. Specific pentru tipul și publicul tău.",
    },
    {
      icon:"🌟", title:"7. Găsește influenceri",
      desc:"La Creatori introduci bugetul, obiectivul și zona geografică și primești o strategie completă cu micro/nano influenceri, mesaj de contact și KPI-uri.",
    },
  ];

  const FAQS = [
    {
      q:"Cât durează să genereze un script?",
      a:"De obicei 10-20 secunde. Creavo caută activ trenduri reale pe internet înainte să scrie — de aceea durează puțin mai mult dar rezultatele sunt actuale.",
    },
    {
      q:"Scripturile sunt în română sau engleză?",
      a:"În română implicit. La Generator poți selecta Engleză dacă vrei să postezi și pe piețe internaționale.",
    },
    {
      q:"Se salvează ce generez?",
      a:"Da, totul se salvează automat în Istoric după fiecare generare, chiar și după ce închizi aplicația.",
    },
    {
      q:"Pot marca scripturile favorite?",
      a:"Da! În Istoric, apasă ⭐ pe orice element. Apoi poți filtra să vezi doar favoritele.",
    },
    {
      q:"Pot trimite scriptul pe WhatsApp direct?",
      a:"Da, după generare apare butonul verde 'Trimite pe WhatsApp' care deschide direct conversația cu textul pregătit.",
    },
  ];

  return (
    <div style={{ animation:"vcpop 0.3s ease" }}>
      <div style={{ textAlign:"center", marginBottom:"24px" }}>
        <div style={{ fontSize:"32px", marginBottom:"8px" }}>❓</div>
        <h2 style={{ margin:"0 0 6px", fontSize:"22px", fontWeight:800, color:T.txt }}>Cum funcționează</h2>
        <p style={{ margin:0, fontSize:"14px", color:T.muted }}>Ghid rapid pentru Creavo</p>
      </div>

      {/* Steps */}
      <div style={{ display:"flex", flexDirection:"column", gap:"10px", marginBottom:"24px" }}>
        {STEPS.map((s,i)=>(
          <div key={i} style={{
            background:T.card, border:`1px solid ${T.bord}`,
            borderRadius:"16px", padding:"16px 18px",
            boxShadow:`0 2px 12px ${T.shadow}`,
          }}>
            <div style={{ display:"flex", alignItems:"center", gap:"12px", marginBottom:"8px" }}>
              <div style={{
                width:"40px", height:"40px", borderRadius:"12px",
                background:`${T.acc}15`, border:`1px solid ${T.acc}25`,
                display:"flex", alignItems:"center", justifyContent:"center",
                fontSize:"20px", flexShrink:0,
              }}>{s.icon}</div>
              <span style={{ fontSize:"14px", fontWeight:700, color:T.txt }}>{s.title}</span>
            </div>
            <p style={{ margin:0, fontSize:"15px", color:T.txt2, lineHeight:1.7 }}>{s.desc}</p>
          </div>
        ))}
      </div>

      {/* FAQ */}
      <h3 style={{ fontSize:"16px", fontWeight:700, color:T.txt, margin:"0 0 12px" }}>Întrebări frecvente</h3>
      <div style={{ display:"flex", flexDirection:"column", gap:"8px" }}>
        {FAQS.map((f,i)=>(
          <div key={i} style={{
            background:T.card, border:`1px solid ${open===i?T.acc:T.bord}`,
            borderRadius:"14px", overflow:"hidden",
            transition:"border-color 0.2s",
          }}>
            <button onClick={()=>setOpen(open===i?null:i)} style={{
              width:"100%", padding:"14px 18px",
              border:"none", background:"transparent",
              display:"flex", justifyContent:"space-between", alignItems:"center",
              cursor:"pointer", fontFamily:"inherit",
            }}>
              <span style={{ fontSize:"14px", fontWeight:600, color:T.txt, textAlign:"left" }}>{f.q}</span>
              <span style={{ color:T.muted, fontSize:"18px", flexShrink:0, marginLeft:"8px" }}>{open===i?"▲":"▼"}</span>
            </button>
            {open===i&&(
              <div style={{ padding:"0 18px 14px", borderTop:`1px solid ${T.bord}` }}>
                <p style={{ margin:"12px 0 0", fontSize:"15px", color:T.txt2, lineHeight:1.7 }}>{f.a}</p>
              </div>
            )}
          </div>
        ))}
      </div>

      <div style={{ marginTop:"20px", padding:"16px", background:`${T.acc}08`, border:`1px solid ${T.acc}20`, borderRadius:"16px", textAlign:"center" }}>
        <p style={{ margin:"0 0 10px", fontSize:"13px", fontWeight:600, color:T.acc }}>Ai nevoie de ajutor?</p>
        <p style={{ margin:"0 0 12px", fontSize:"12px", color:T.muted }}>Scrie-ne pe WhatsApp și te ajutăm în maxim 24h</p>
        <button onClick={()=>window.open("https://wa.me/40720948636","_blank")} style={{
          display:"inline-flex",alignItems:"center",gap:"8px",
          padding:"12px 24px",borderRadius:"12px",border:"none",
          background:"#25D366",color:"#fff",
          fontSize:"14px",fontWeight:700,cursor:"pointer",fontFamily:"inherit",
          boxShadow:"0 4px 16px rgba(37,211,102,0.4)",
        }}>
          <span style={{fontSize:"18px"}}>📱</span>
          0720 948 636
        </button>
      </div>
    </div>
  );
}

// ═════════════════════════════════════════════════════════════════════════════
// TUTORIAL OVERLAY — prima utilizare
// ═════════════════════════════════════════════════════════════════════════════
function TutorialOverlay({ T, onDone }) {
  const [step, setStep] = useState(0);

  const STEPS = [
    {
      emoji:"👋",
      color:T.acc,
      title:"Bine ai venit în Creavo!",
      desc:"Îți arătăm în 4 pași simpli cum să generezi primul tău script viral. Durează 2 minute.",
      tip:null,
    },
    {
      emoji:"✏️",
      color:T.teal,
      title:"Scrie numele afacerii tale",
      desc:"La ⚡ Generator, primul câmp este pentru numele afacerii tale. Scrie exact cum se numește — AI-ul va folosi acest nume în tot scriptul.",
      tip:"💡 Ex: numele exact al afacerii tale — AI-ul îl va folosi în tot scriptul",
    },
    {
      emoji:"🎯",
      color:T.pink,
      title:"Alege tipul și apasă Generează",
      desc:"Selectează tipul afacerii, platforma (TikTok sau Instagram), durata și apasă butonul violet. În 15-20 secunde primești un script complet.",
      tip:"💡 Începe cu templateul Generic — funcționează pentru orice afacere",
    },
    {
      emoji:"📋",
      color:T.gold,
      title:"Copiază și filmează",
      desc:"După generare, copiază scriptul cu un singur tap sau trimite-l direct pe WhatsApp. Ai exact ce să spui în fața camerei.",
      tip:"💡 Butonul verde trimite scriptul pe WhatsApp în 2 secunde",
    },
    {
      emoji:"👤",
      color:T.green,
      title:"Completează profilul o singură dată",
      desc:"Mergi la Profil și completează numele afacerii și platforma preferată. De acum înainte câmpurile se completează automat la fiecare generare.",
      tip:"💡 Economisești timp la fiecare utilizare",
    },
  ];

  const s = STEPS[step];
  const isLast = step === STEPS.length - 1;

  return (
    <div style={{
      position:"fixed",inset:0,zIndex:1000,
      background:"rgba(0,0,0,0.82)",
      backdropFilter:"blur(6px)",
      display:"flex",alignItems:"flex-end",justifyContent:"center",
      padding:"0 16px 100px",
    }}>
      <div style={{
        background:T.card,
        borderRadius:"28px",
        padding:"26px",
        width:"100%",maxWidth:"448px",
        boxShadow:`0 -12px 48px rgba(0,0,0,0.6), 0 0 0 1px ${T.bord}`,
        animation:"vcpop 0.35s ease",
      }}>
        {/* Header */}
        <div style={{display:"flex",alignItems:"center",gap:"14px",marginBottom:"18px"}}>
          <div style={{
            width:"56px",height:"56px",borderRadius:"18px",flexShrink:0,
            background:`linear-gradient(135deg,${s.color}25,${s.color}10)`,
            border:`2px solid ${s.color}40`,
            display:"flex",alignItems:"center",justifyContent:"center",
            fontSize:"28px",
            boxShadow:`0 4px 16px ${s.color}30`,
          }}>{s.emoji}</div>
          <div style={{flex:1}}>
            <div style={{fontSize:"17px",fontWeight:800,color:T.txt,lineHeight:1.2}}>{s.title}</div>
            <div style={{fontSize:"12px",color:T.muted,marginTop:"4px",fontWeight:500}}>
              Pasul {step+1} din {STEPS.length}
            </div>
          </div>
        </div>

        {/* Description */}
        <p style={{fontSize:"15px",color:T.txt2,lineHeight:1.75,margin:"0 0 14px"}}>{s.desc}</p>

        {/* Tip */}
        {s.tip&&(
          <div style={{
            padding:"10px 14px",borderRadius:"12px",marginBottom:"18px",
            background:`${s.color}12`,border:`1px solid ${s.color}25`,
            fontSize:"13px",color:s.color,fontWeight:500,lineHeight:1.5,
          }}>{s.tip}</div>
        )}

        {/* Progress + button */}
        <div style={{display:"flex",alignItems:"center",gap:"10px"}}>
          <div style={{flex:1,display:"flex",gap:"5px"}}>
            {STEPS.map((_,i)=>(
              <div key={i} onClick={()=>setStep(i)} style={{
                height:"5px",
                flex:i===step?2.5:1,
                borderRadius:"3px",
                background:i<step?T.acc:i===step?s.color:T.bord,
                transition:"all 0.3s",
                cursor:"pointer",
              }}/>
            ))}
          </div>
          <button onClick={()=>isLast?onDone():setStep(s=>s+1)} style={{
            padding:"12px 24px",borderRadius:"14px",border:"none",
            background:`linear-gradient(135deg,${s.color},${s.color}cc)`,
            color:"#fff",fontSize:"14px",fontWeight:700,
            cursor:"pointer",fontFamily:"inherit",minHeight:"48px",
            boxShadow:`0 4px 18px ${s.color}50`,
            flexShrink:0,
          }}>{isLast?"Să începem! 🚀":"Următor →"}</button>
        </div>

        <button onClick={onDone} style={{
          width:"100%",marginTop:"12px",padding:"10px",
          background:"transparent",border:"none",color:T.muted,
          fontSize:"13px",cursor:"pointer",fontFamily:"inherit",
        }}>Sari peste — știu deja cum funcționează</button>
      </div>
    </div>
  );
}

// ═════════════════════════════════════════════════════════════════════════════
// FEEDBACK TAB
// ═════════════════════════════════════════════════════════════════════════════
function FeedbackTab({ T }) {
  const [rating, setRating]   = useState(0);
  const [best,   setBest]     = useState("");
  const [improve,setImprove]  = useState("");
  const [missing,setMissing]  = useState("");
  const [sent,   setSent]     = useState(false);
  const [loading,setLoading]  = useState(false);

  async function send() {
    if (!rating) return;
    setLoading(true);
    try {
      const text = encodeURIComponent(
        "📊 FEEDBACK CREAVO BETA\n\n" +
        "⭐ Notă: " + rating + "/5\n\n" +
        "✅ Ce a plăcut:\n" + (best||"—") + "\n\n" +
        "🔧 De îmbunătățit:\n" + (improve||"—") + "\n\n" +
        "➕ Ce lipsește:\n" + (missing||"—")
      );
      window.open("https://wa.me/40720948636?text=" + text, "_blank");
      setSent(true);
      phCapture("feedback_sent", { rating });
    } catch(e) {}
    setLoading(false);
  }

  if (sent) return (
    <div style={{textAlign:"center",padding:"60px 20px",animation:"vcpop 0.3s ease"}}>
      <div style={{fontSize:"64px",marginBottom:"16px"}}>🙏</div>
      <h2 style={{margin:"0 0 10px",fontSize:"22px",fontWeight:800,color:T.txt}}>Mulțumim!</h2>
      <p style={{fontSize:"15px",color:T.txt2,lineHeight:1.7,margin:"0 0 24px"}}>Feedback-ul tău ne ajută să îmbunătățim Creavo pentru toată lumea.</p>
      <button onClick={()=>setSent(false)} style={{
        padding:"13px 28px",borderRadius:"14px",border:`1.5px solid ${T.bord}`,
        background:T.faint,color:T.txt2,fontSize:"14px",fontWeight:600,
        cursor:"pointer",fontFamily:"inherit",
      }}>Trimite alt feedback</button>
    </div>
  );

  return (
    <div style={{animation:"vcpop 0.3s ease"}}>
      <div style={{textAlign:"center",marginBottom:"24px"}}>
        <div style={{fontSize:"32px",marginBottom:"8px"}}>💬</div>
        <h2 style={{margin:"0 0 6px",fontSize:"22px",fontWeight:800,color:T.txt}}>Feedback</h2>
        <p style={{margin:0,fontSize:"14px",color:T.muted}}>Ajută-ne să îmbunătățim Creavo</p>
      </div>

      {/* Rating */}
      <div style={{background:T.card,border:`1px solid ${T.bord}`,borderRadius:"18px",padding:"20px",marginBottom:"14px"}}>
        <Lbl color={T.muted}>Cât de mulțumit ești de aplicație?</Lbl>
        <div style={{display:"flex",justifyContent:"center",gap:"12px",marginTop:"4px"}}>
          {[1,2,3,4,5].map(n=>(
            <button key={n} onClick={()=>setRating(n)} style={{
              width:"52px",height:"52px",borderRadius:"14px",border:"none",
              background:rating>=n?`${T.gold}20`:T.faint,
              fontSize:"28px",cursor:"pointer",
              transition:"all 0.15s",
              transform:rating>=n?"scale(1.15)":"scale(1)",
            }}>⭐</button>
          ))}
        </div>
        {rating>0&&<p style={{textAlign:"center",margin:"12px 0 0",fontSize:"14px",color:T.gold,fontWeight:700}}>
          {["","Slab 😕","Mediocru 😐","Bun 🙂","Foarte bun 😊","Excelent 🤩"][rating]}
        </p>}
      </div>

      <div style={{display:"flex",flexDirection:"column",gap:"12px",marginBottom:"20px"}}>
        <div style={{background:T.card,border:`1px solid ${T.bord}`,borderRadius:"16px",padding:"16px"}}>
          <Lbl color={T.green}>Ce ți-a plăcut cel mai mult?</Lbl>
          <MTextarea value={best} onChange={e=>setBest(e.target.value)} placeholder="ex: Scripturile sunt foarte specifice pentru afacerea mea..." rows={2} T={T}/>
        </div>
        <div style={{background:T.card,border:`1px solid ${T.bord}`,borderRadius:"16px",padding:"16px"}}>
          <Lbl color={T.gold}>Ce ar trebui îmbunătățit?</Lbl>
          <MTextarea value={improve} onChange={e=>setImprove(e.target.value)} placeholder="ex: Butoanele ar putea fi mai mari..." rows={2} T={T}/>
        </div>
        <div style={{background:T.card,border:`1px solid ${T.bord}`,borderRadius:"16px",padding:"16px"}}>
          <Lbl color={T.pink}>Ce funcție îți lipsește?</Lbl>
          <MTextarea value={missing} onChange={e=>setMissing(e.target.value)} placeholder="ex: Aș vrea să pot salva scriptul ca imagine..." rows={2} T={T}/>
        </div>
      </div>

      <PBtn T={T} onClick={send} disabled={!rating||loading} full>
        {loading?"Se trimite...":"📱 Trimite Feedback pe WhatsApp"}
      </PBtn>
      <p style={{textAlign:"center",fontSize:"12px",color:T.muted,margin:"10px 0 0"}}>Feedback-ul se trimite direct pe WhatsApp-ul nostru</p>
    </div>
  );
}

// ═════════════════════════════════════════════════════════════════════════════
// DESPRE + TERMENI + CONFIDENȚIALITATE
// ═════════════════════════════════════════════════════════════════════════════
function DespreTab({ T }) {
  const [section, setSection] = useState("despre");
  const SECTIONS = [
    { id:"despre",   label:"Despre" },
    { id:"termeni",  label:"Termeni" },
    { id:"gdpr",     label:"GDPR" },
  ];
  return (
    <div style={{animation:"vcpop 0.3s ease"}}>
      <div style={{display:"flex",gap:"6px",marginBottom:"20px"}}>
        {SECTIONS.map(s=>(
          <button key={s.id} onClick={()=>setSection(s.id)} style={{
            flex:1,padding:"10px",borderRadius:"12px",border:"none",
            background:section===s.id?`${T.acc}15`:T.faint,
            color:section===s.id?T.acc:T.muted,
            fontSize:"13px",fontWeight:section===s.id?700:400,
            cursor:"pointer",fontFamily:"inherit",minHeight:"44px",
            borderBottom:section===s.id?`2px solid ${T.acc}`:"2px solid transparent",
          }}>{s.label}</button>
        ))}
      </div>

      {section==="despre"&&(
        <div>
          <div style={{textAlign:"center",marginBottom:"24px"}}>
            <div style={{width:"80px",height:"80px",borderRadius:"24px",background:"#0f0d1e",margin:"0 auto 16px",display:"flex",alignItems:"center",justifyContent:"center"}}>
              <svg width="50" height="50" viewBox="0 0 38 38">
                <defs><linearGradient id="lg_d" x1="0%" y1="0%" x2="100%" y2="100%"><stop offset="0%" stopColor="#7c6df0"/><stop offset="100%" stopColor="#f472b6"/></linearGradient></defs>
                <rect x="7" y="26" width="5" height="8" rx="1.5" fill="url(#lg_d)" opacity="0.5"/>
                <rect x="15" y="19" width="5" height="15" rx="1.5" fill="url(#lg_d)" opacity="0.75"/>
                <rect x="23" y="12" width="5" height="22" rx="1.5" fill="url(#lg_d)"/>
              </svg>
            </div>
            <h2 style={{margin:"0 0 4px",fontSize:"24px",fontWeight:800,background:`linear-gradient(135deg,#7c6df0,#f472b6)`,WebkitBackgroundClip:"text",WebkitTextFillColor:"transparent",color:"#7c6df0"}}>creavo</h2>
            <p style={{margin:0,fontSize:"13px",color:T.muted,letterSpacing:"3px"}}>AI CONTENT · Beta</p>
          </div>
          {[
            {icon:"🎯",title:"Ce este Creavo?",desc:"Creavo este o aplicație de inteligență artificială care ajută afacerile din România să creeze conținut viral pentru TikTok și Instagram — scripturi, hook-uri, calendare editoriale și strategii de influencer marketing."},
            {icon:"🏙️",title:"Cine suntem?",desc:"Suntem o echipă din Târgu Jiu care a creat Creavo pentru antreprenorii și micile afaceri din România care vor să fie prezenți pe social media dar nu știu ce să posteze."},
            {icon:"📞",title:"Contact și suport",desc:"Pentru orice problemă sau întrebare, ne poți contacta direct pe WhatsApp la numărul 0720 948 636. Răspundem în maxim 24 de ore."},
            {icon:"🔄",title:"Versiunea Beta",desc:"Aplicația este în stadiu Beta — testăm și îmbunătățim constant. Feedback-ul tău este esențial pentru noi. Folosește tab-ul Feedback pentru a ne spune ce crezi."},
          ].map((item,i)=>(
            <div key={i} style={{background:T.card,border:`1px solid ${T.bord}`,borderRadius:"16px",padding:"16px 18px",marginBottom:"10px"}}>
              <div style={{display:"flex",gap:"12px",alignItems:"flex-start"}}>
                <span style={{fontSize:"24px",flexShrink:0}}>{item.icon}</span>
                <div>
                  <div style={{fontSize:"15px",fontWeight:700,color:T.txt,marginBottom:"6px"}}>{item.title}</div>
                  <p style={{margin:0,fontSize:"14px",color:T.txt2,lineHeight:1.7}}>{item.desc}</p>
                </div>
              </div>
            </div>
          ))}
          <button onClick={()=>window.open("https://wa.me/40720948636","_blank")} style={{
            width:"100%",padding:"14px",borderRadius:"14px",border:"none",
            background:"#25D366",color:"#fff",fontSize:"15px",fontWeight:700,
            cursor:"pointer",fontFamily:"inherit",marginTop:"8px",minHeight:"54px",
            display:"flex",alignItems:"center",justifyContent:"center",gap:"8px",
            boxShadow:"0 4px 20px rgba(37,211,102,0.4)",
          }}>📱 Contactează-ne pe WhatsApp</button>
        </div>
      )}

      {section==="termeni"&&(
        <div style={{display:"flex",flexDirection:"column",gap:"10px"}}>
          {[
            {t:"1. Acceptarea termenilor",d:"Prin utilizarea aplicației Creavo, ești de acord cu acești termeni și condiții. Dacă nu ești de acord, te rugăm să nu utilizezi aplicația."},
            {t:"2. Utilizarea aplicației",d:"Creavo este destinat exclusiv creării de conținut pentru social media în scopuri legale și legitime. Orice utilizare abuzivă este interzisă."},
            {t:"3. Conținut generat",d:"Conținutul generat de Creavo folosind AI este orientativ. Tu ești responsabil pentru conținutul pe care îl postezi pe rețelele sociale."},
            {t:"4. Proprietate intelectuală",d:"Creavo și logo-ul său sunt proprietatea exclusivă a echipei noastre. Conținutul generat pentru afacerea ta îți aparține."},
            {t:"5. Limitarea răspunderii",d:"Creavo nu garantează rezultate specifice din utilizarea aplicației. Succesul pe social media depinde de mulți factori."},
            {t:"6. Modificări",d:"Ne rezervăm dreptul de a modifica acești termeni oricând. Continuarea utilizării aplicației reprezintă acceptul modificărilor."},
          ].map((item,i)=>(
            <div key={i} style={{background:T.card,border:`1px solid ${T.bord}`,borderRadius:"14px",padding:"14px 16px"}}>
              <div style={{fontSize:"14px",fontWeight:700,color:T.txt,marginBottom:"6px"}}>{item.t}</div>
              <p style={{margin:0,fontSize:"13px",color:T.txt2,lineHeight:1.65}}>{item.d}</p>
            </div>
          ))}
        </div>
      )}

      {section==="gdpr"&&(
        <div style={{display:"flex",flexDirection:"column",gap:"10px"}}>
          {[
            {t:"Date colectate",d:"Colectăm doar datele pe care le introduci voluntar în aplicație: numele afacerii, tipul afacerii și preferințele tale. Nu colectăm date personale fără consimțământ."},
            {t:"Stocarea datelor",d:"Toate datele tale sunt stocate local pe dispozitivul tău (localStorage). Nu trimitem datele pe serverele noastre, cu excepția feedback-ului trimis voluntar."},
            {t:"Analytics",d:"Folosim PostHog pentru analytics anonim — urmărim ce funcții sunt folosite, nu cine le folosește. Poți dezactiva cookies din setările browserului."},
            {t:"Drepturile tale",d:"Conform GDPR, ai dreptul de acces, rectificare și ștergere a datelor. Poți șterge toate datele din Profil → Șterge istoricul, sau prin ștergerea datelor browserului."},
            {t:"Contact GDPR",d:"Pentru orice solicitare legată de datele tale personale, contactează-ne la 0720 948 636 sau pe WhatsApp."},
          ].map((item,i)=>(
            <div key={i} style={{background:T.card,border:`1px solid ${T.bord}`,borderRadius:"14px",padding:"14px 16px"}}>
              <div style={{fontSize:"14px",fontWeight:700,color:T.txt,marginBottom:"6px"}}>🔒 {item.t}</div>
              <p style={{margin:0,fontSize:"13px",color:T.txt2,lineHeight:1.65}}>{item.d}</p>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// Render app
const rootEl = document.getElementById('root');
const root = ReactDOM.createRoot(rootEl);
root.render(React.createElement(App));
