// Cavivo workspace dashboard

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "greetingStyle": "serif-italic",
  "showAmbientBlobs": true,
  "starterDensity": "regular",
  "inputGlow": true
} /*EDITMODE-END*/;

// ─── Icons (line-style, 20×20) ──────────────────────────────────────────────
const Icon = ({ d, size = 20, stroke = 1.6, fill = "none" }) =>
<svg width={size} height={size} viewBox="0 0 24 24" fill={fill} stroke="currentColor"
strokeWidth={stroke} strokeLinecap="round" strokeLinejoin="round">{d}</svg>;


const I = {
  home: <Icon d={<><path d="M3 11.5 12 4l9 7.5" /><path d="M5 10v10h14V10" /></>} />,
  work: <Icon d={<><rect x="3" y="5" width="18" height="15" rx="2" /><path d="M3 9h18" /><path d="M8 3v4M16 3v4" /></>} />,
  more: <Icon d={<><circle cx="5" cy="12" r="1.2" fill="currentColor" /><circle cx="12" cy="12" r="1.2" fill="currentColor" /><circle cx="19" cy="12" r="1.2" fill="currentColor" /></>} />,
  spark: <Icon d={<><path d="M12 3v4M12 17v4M3 12h4M17 12h4M5.6 5.6l2.8 2.8M15.6 15.6l2.8 2.8M5.6 18.4l2.8-2.8M15.6 8.4l2.8-2.8" /></>} />,
  bulb: <Icon d={<><path d="M9 18h6M10 21h4" /><path d="M12 3a6 6 0 0 0-4 10.5c.7.7 1 1.5 1 2.5h6c0-1 .3-1.8 1-2.5A6 6 0 0 0 12 3Z" /></>} />,
  flow: <Icon d={<><circle cx="6" cy="6" r="2.5" /><circle cx="18" cy="6" r="2.5" /><circle cx="12" cy="18" r="2.5" /><path d="M7.5 7.5 11 15.5M16.5 7.5 13 15.5" /></>} />,
  bot: <Icon d={<><rect x="4" y="8" width="16" height="11" rx="3" /><path d="M12 4v4M9 13h.01M15 13h.01M9 16h6" /></>} />,
  pen: <Icon d={<><path d="M4 20h4l11-11-4-4L4 16Z" /><path d="M14 6l4 4" /></>} />,
  search: <Icon d={<><circle cx="11" cy="11" r="7" /><path d="m20 20-3.5-3.5" /></>} />,
  bell: <Icon d={<><path d="M6 16V11a6 6 0 1 1 12 0v5l1.5 2h-15Z" /><path d="M10 20a2 2 0 0 0 4 0" /></>} />,
  invite: <Icon d={<><circle cx="9" cy="9" r="3.5" /><path d="M3 19c0-3 2.5-5 6-5s6 2 6 5" /><path d="M18 8v4M16 10h4" /></>} />,
  help: <Icon d={<><circle cx="12" cy="12" r="9" /><path d="M9.5 9.5a2.5 2.5 0 1 1 3.5 2.3c-.8.4-1 1-1 1.7" /><circle cx="12" cy="17" r=".6" fill="currentColor" /></>} />,
  grid: <Icon d={<><rect x="4" y="4" width="6" height="6" rx="1.2" /><rect x="14" y="4" width="6" height="6" rx="1.2" /><rect x="4" y="14" width="6" height="6" rx="1.2" /><rect x="14" y="14" width="6" height="6" rx="1.2" /></>} />,
  mic: <Icon d={<><rect x="9" y="3" width="6" height="11" rx="3" /><path d="M5 11a7 7 0 0 0 14 0M12 18v3" /></>} />,
  send: <Icon d={<><path d="m4 12 16-8-6 16-2.5-6.5L4 12Z" /></>} />,
  attach: <Icon d={<><path d="M21 11.5 12.5 20a5 5 0 1 1-7-7l9-9a3.5 3.5 0 1 1 5 5l-8.5 8.5a2 2 0 0 1-3-3l8-8" /></>} />,
  emoji: <Icon d={<><circle cx="12" cy="12" r="9" /><path d="M8 14c1 1.5 2.5 2.2 4 2.2s3-.7 4-2.2" /><circle cx="9" cy="10" r=".7" fill="currentColor" /><circle cx="15" cy="10" r=".7" fill="currentColor" /></>} />,
  sliders: <Icon d={<><path d="M4 6h10M18 6h2M4 12h2M10 12h10M4 18h12M20 18h0M16 18h4"/><circle cx="16" cy="6" r="2" fill="#fff"/><circle cx="8" cy="12" r="2" fill="#fff"/><circle cx="14" cy="18" r="2" fill="#fff"/></>} stroke={1.8}/>,
  app: <Icon d={<><rect x="3" y="3" width="8" height="8" rx="1.5" /><rect x="13" y="3" width="8" height="8" rx="1.5" /><rect x="3" y="13" width="8" height="8" rx="1.5" /><circle cx="17" cy="17" r="4" /></>} />,
  chevDown: <Icon d={<><path d="m6 9 6 6 6-6" /></>} />,
  chevUpDown: <Icon d={<><path d="m8 9 4-4 4 4M8 15l4 4 4-4" /></>} size={14} />,
  plus: <Icon d={<><path d="M12 5v14M5 12h14" /></>} />,
  // Tile icons (filled-on-color, white stroke)
  board: <Icon d={<><rect x="3" y="5" width="18" height="14" rx="2.5" /><path d="M8 5v14M3 11h5" /></>} stroke={1.8} />,
  doc: <Icon d={<><path d="M6 3h8l4 4v14H6Z" /><path d="M14 3v4h4M9 12h6M9 16h4" /></>} stroke={1.8} />,
  zoom: <Icon d={<><circle cx="11" cy="11" r="6" /><path d="m20 20-4-4M11 8v6M8 11h6" /></>} stroke={1.8} />,
  chart: <Icon d={<><rect x="3" y="3" width="18" height="18" rx="2.5" /><path d="M8 16v-4M12 16V8M16 16v-7" /></>} stroke={1.8} />,
  idea: <Icon d={<><path d="M9 18h6M10 21h4" /><path d="M12 3a6 6 0 0 0-4 10.5c.7.7 1 1.5 1 2.5h6c0-1 .3-1.8 1-2.5A6 6 0 0 0 12 3Z" /></>} stroke={1.8} />,
  image: <Icon d={<><rect x="3" y="4" width="18" height="16" rx="2.5" /><circle cx="9" cy="10" r="1.6" /><path d="m3 17 5-5 4 4 3-3 6 6" /></>} stroke={1.8} />,
  wave: <Icon d={<><path d="M3 12c2 0 2-4 4-4s2 8 4 8 2-12 4-12 2 8 4 8 2-4 4-4" /></>} stroke={1.8} />,
  book: <Icon d={<><path d="M4 4h6a4 4 0 0 1 4 4v13" /><path d="M20 4h-6a4 4 0 0 0-4 4v13" /><path d="M4 4v15h6M20 4v15h-6" /></>} stroke={1.8} />,
  phone: <Icon d={<><rect x="7" y="3" width="10" height="18" rx="2" /><path d="M10 18h4" /></>} size={18} />,
  pin: <Icon d={<><path d="M12 21s-6-5.3-6-10a6 6 0 1 1 12 0c0 4.7-6 10-6 10Z" /><circle cx="12" cy="11" r="2" /></>} size={18} />,
  heart: <Icon d={<><path d="M12 20s-7-4.4-7-10a4 4 0 0 1 7-2.7A4 4 0 0 1 19 10c0 5.6-7 10-7 10Z" /></>} size={18} />,
  edit: <Icon d={<><path d="M4 20h4l11-11-4-4L4 16Z" /></>} size={18} />,
  list: <Icon d={<><path d="M4 7h16M4 12h10M4 17h16" /></>} size={18} />,
  sparkle: <Icon d={<><path d="M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8Z" /></>} stroke={1.5} />,
  diamond: <Icon d={<><path d="M12 3 4 11l8 10 8-10Z" /><path d="M4 11h16M9 11l3-8M15 11l-3-8" /></>} size={16} stroke={1.4} />
};

// ─── Logo ───────────────────────────────────────────────────────────────────
const CavivoLogo = ({ size = 32 }) =>
<div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
    <svg width={size} height={size} viewBox="0 0 40 40">
      <defs>
        <linearGradient id="cl" x1="0" x2="1" y1="0" y2="1">
          <stop offset="0" stopColor="#C8B6FF" />
          <stop offset=".5" stopColor="#F5B8D0" />
          <stop offset="1" stopColor="#FFD4A8" />
        </linearGradient>
      </defs>
      <path d="M20 4c8.8 0 16 7.2 16 16 0 4-3 5-7 5s-5-2-9-2-5 4-9 4-7-2-7-7c0-8.8 7.2-16 16-16Z" fill="url(#cl)" />
      <circle cx="14" cy="18" r="2.4" fill="#1c1c1c" />
      <circle cx="24" cy="18" r="2.4" fill="#1c1c1c" />
    </svg>
    <div style={{ lineHeight: 1 }}>
      <div style={{ fontFamily: '"Instrument Serif", serif', fontSize: 22, fontStyle: 'italic', color: '#1c1c1c', letterSpacing: '-.01em' }}>Cavivo</div>
      <div style={{ fontSize: 9.5, color: '#9089A0', letterSpacing: '.14em', textTransform: 'uppercase', marginTop: 2, fontWeight: 500 }}>Creative OS</div>
    </div>
  </div>;


// ─── Sidebar ────────────────────────────────────────────────────────────────
const SidebarItem = ({ icon, label, active, onClick, badge }) =>
<button onClick={onClick}
style={{ display: 'flex', alignItems: 'center', gap: 12, width: '100%', padding: '10px 12px',
  borderRadius: 10, border: 'none', cursor: 'pointer',
  background: active ? '#FFFFFF' : 'transparent',
  boxShadow: active ? '0 1px 2px rgba(28,28,28,.06), 0 0 0 1px #E0DAE8' : 'none',
  color: active ? '#1c1c1c' : '#4a4356',
  fontSize: 13.5, fontWeight: active ? 600 : 500, fontFamily: 'inherit',
  transition: 'background .15s' }}
onMouseEnter={(e) => {if (!active) e.currentTarget.style.background = 'rgba(255,255,255,.55)';}}
onMouseLeave={(e) => {if (!active) e.currentTarget.style.background = 'transparent';}}>
    <span style={{ color: active ? '#7A5AE0' : '#6b6377', display: 'flex' }}>{icon}</span>
    <span style={{ flex: 1, textAlign: 'left' }}>{label}</span>
    {badge && <span style={{ fontSize: 10, fontWeight: 600, color: '#7A5AE0', background: '#E8DFFA', padding: '2px 7px', borderRadius: 999 }}>{badge}</span>}
  </button>;


const SectionLabel = ({ children }) =>
<div style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '14px 12px 6px', color: '#9089A0', fontSize: 11, fontWeight: 600, letterSpacing: '.08em', textTransform: 'uppercase' }}>
    <span>{children}</span>
    <span style={{ color: '#C9C2D4' }}>{I.chevDown}</span>
  </div>;


const Sidebar = ({ active, setActive }) =>
<aside style={{ width: 264, flexShrink: 0, background: '#F7F2FB', borderRight: '1px solid #E0DAE8',
  display: 'flex', flexDirection: 'column', padding: '18px 14px 14px' }}>
    <div style={{ padding: '2px 4px 14px', borderBottom: '1px solid #E0DAE8', marginBottom: 14 }}>
      <CavivoLogo />
    </div>

    <SidebarItem icon={I.home} label="Home" active={active === 'home'} onClick={() => setActive('home')} />
    <SidebarItem icon={I.work} label="My work" active={active === 'work'} onClick={() => setActive('work')} />
    <SidebarItem icon={I.more} label="More" active={active === 'more'} onClick={() => setActive('more')} />

    <SidebarItem icon={I.flow} label="AI Workflows" active={active === 'flow'} onClick={() => setActive('flow')} />
    <SidebarItem icon={I.bot} label="AI Agents" active={active === 'agents'} onClick={() => setActive('agents')} />
    <SidebarItem icon={I.pen} label="AI Notetaker" active={active === 'notes'} onClick={() => setActive('notes')} />
  </aside>;


// ─── Top bar ────────────────────────────────────────────────────────────────
const IconBtn = ({ children, onClick, title }) =>
<button onClick={onClick} title={title}
style={{ width: 38, height: 38, borderRadius: 10, border: '1px solid #E0DAE8',
  background: '#FFFFFF', cursor: 'pointer', color: '#4a4356',
  display: 'flex', alignItems: 'center', justifyContent: 'center',
  transition: 'transform .12s, background .12s' }}
onMouseEnter={(e) => {e.currentTarget.style.background = '#FAF7FE';}}
onMouseLeave={(e) => {e.currentTarget.style.background = '#FFFFFF';}}>
    {children}
  </button>;


const TopBar = ({ user, onSignIn, onSignOut }) => {
  const name = user?.user_metadata?.full_name
    || user?.user_metadata?.name
    || user?.email?.split('@')[0]
    || 'Guest';
  const initial = (name[0] || 'G').toUpperCase();

  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '18px 32px 0' }}>
      <button style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '9px 14px 9px 11px',
        background: '#FFFFFF', border: '1px solid #E0DAE8', borderRadius: 10, cursor: 'pointer',
        fontFamily: 'inherit', fontSize: 13, color: '#1c1c1c', fontWeight: 500,
        boxShadow: '0 1px 2px rgba(28,28,28,.03)' }}>
        <span style={{ color: '#7A5AE0' }}>{I.diamond}</span>
        See plans
      </button>
      <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
        {user ? (
          <>
            <span style={{ fontSize: 13, color: '#6b6377', maxWidth: 180, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
              {name}
            </span>
            <button
              onClick={onSignOut}
              style={{ padding: '8px 12px', borderRadius: 10, border: '1px solid #E0DAE8', background: '#FFFFFF',
                cursor: 'pointer', fontFamily: 'inherit', fontSize: 12.5, fontWeight: 600, color: '#4a4356' }}>
              Sign out
            </button>
          </>
        ) : (
          <button
            onClick={onSignIn}
            style={{ padding: '9px 14px', borderRadius: 10, border: 'none', cursor: 'pointer',
              fontFamily: 'inherit', fontSize: 13, fontWeight: 600, color: '#1c1c1c',
              background: 'linear-gradient(120deg,#C8B6FF 0%,#F5B8D0 50%,#C8B6FF 100%)' }}>
            Sign in
          </button>
        )}
        <button
          onClick={user ? onSignOut : onSignIn}
          title={user ? 'Account' : 'Sign in'}
          style={{ width: 40, height: 40, borderRadius: 10, border: '1px solid #E0DAE8', cursor: 'pointer',
            padding: 2, background: '#FFFFFF', overflow: 'hidden' }}>
          {user?.user_metadata?.avatar_url ? (
            <img src={user.user_metadata.avatar_url} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', borderRadius: 8 }} />
          ) : (
            <div style={{ width: '100%', height: '100%', borderRadius: 8,
              background: 'linear-gradient(135deg,#FFD4A8 0%,#F5B8D0 50%,#C8B6FF 100%)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              color: '#fff', fontWeight: 700, fontSize: 13 }}>{initial}</div>
          )}
        </button>
      </div>
    </div>
  );
};


// ─── Quick action tile (small, top row) ─────────────────────────────────────
const QuickTile = ({ icon, label, color, onClick, href }) => {
  const [hover, setHover] = React.useState(false);
  const Tag = href ? 'a' : 'button';
  const tagProps = href ? { href } : { onClick };
  return (
    <Tag {...tagProps}
    onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
    style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8,
      background: 'transparent', border: 'none', cursor: 'pointer', textDecoration:'none',
      padding: '6px 4px', fontFamily: 'inherit',
      transform: hover ? 'translateY(-2px)' : 'translateY(0)',
      transition: 'transform .18s' }}>
      <div style={{ width: 54, height: 54, borderRadius: 14, background: color.bg,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        color: color.fg,
        boxShadow: hover ?
        `0 8px 22px ${color.shadow}, 0 0 0 1px ${color.ring}` :
        `0 2px 6px ${color.shadow}, 0 0 0 1px ${color.ring}`,
        transition: 'box-shadow .18s' }}>
        {icon}
      </div>
      <div style={{ fontSize: 11.5, color: '#4a4356', fontWeight: 500, letterSpacing: '-.005em' }}>{label}</div>
    </Tag>);

};

// ─── Starter card (large, gradient) ─────────────────────────────────────────
const StarterCard = ({ icon, title, body, palette, onClick }) => {
  const [hover, setHover] = React.useState(false);
  return (
    <button onClick={onClick}
    onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
    style={{ position: 'relative', overflow: 'hidden', textAlign: 'left',
      background: palette.bg,
      border: '1px solid ' + palette.border,
      borderRadius: 18, padding: '18px 18px 20px', cursor: 'pointer',
      fontFamily: 'inherit', color: palette.ink, minHeight: 158,
      boxShadow: hover ? `0 14px 30px ${palette.shadow}` : `0 2px 6px ${palette.shadow}`,
      transform: hover ? 'translateY(-3px)' : 'translateY(0)',
      transition: 'transform .2s, box-shadow .2s' }}>
      {/* Ambient blob */}
      <div style={{ position: 'absolute', right: -30, bottom: -40, width: 180, height: 180, borderRadius: '50%',
        background: palette.blob, filter: 'blur(20px)', opacity: .65, pointerEvents: 'none' }} />
      <div style={{ position: 'relative' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 }}>
          <div style={{ width: 34, height: 34, borderRadius: 9,
            background: palette.iconBg,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: palette.iconFg }}>{icon}</div>
          <div style={{ fontWeight: 600, fontSize: 15.5, letterSpacing: '-.01em' }}>{title}</div>
        </div>
        <div style={{ fontSize: 12.5, lineHeight: 1.55, color: palette.body, maxWidth: '92%' }}>{body}</div>
      </div>
      {/* Hover arrow */}
      <div style={{ position: 'absolute', top: 18, right: 18, opacity: hover ? 1 : 0, transition: 'opacity .18s',
        color: palette.ink }}>
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M7 17 17 7M9 7h8v8" />
        </svg>
      </div>
    </button>);

};

// ─── Palettes for cards ─────────────────────────────────────────────────────
const lavenderP = {
  bg: 'linear-gradient(135deg,#E8DFFA 0%,#F0E5F8 100%)',
  blob: 'radial-gradient(circle,#C8B6FF 0%,transparent 70%)',
  border: 'rgba(200,182,255,.5)',
  iconBg: 'rgba(255,255,255,.7)', iconFg: '#7A5AE0',
  ink: '#3D2A6B', body: '#5B4A8A',
  shadow: 'rgba(122,90,224,.18)'
};
const pinkP = {
  bg: 'linear-gradient(135deg,#FCE0EC 0%,#F5B8D0 100%)',
  blob: 'radial-gradient(circle,#F5B8D0 0%,transparent 70%)',
  border: 'rgba(245,184,208,.55)',
  iconBg: 'rgba(255,255,255,.7)', iconFg: '#C4407A',
  ink: '#6B2A4A', body: '#8A4A6A',
  shadow: 'rgba(196,64,122,.18)'
};
const mintP = {
  bg: 'linear-gradient(135deg,#D6F0F5 0%,#B5E5D6 100%)',
  blob: 'radial-gradient(circle,#B5E5D6 0%,transparent 70%)',
  border: 'rgba(181,229,214,.6)',
  iconBg: 'rgba(255,255,255,.7)', iconFg: '#2A8060',
  ink: '#1F4D3D', body: '#3D6A5A',
  shadow: 'rgba(42,128,96,.16)'
};
const peachP = {
  bg: 'linear-gradient(135deg,#FFE8DC 0%,#FFD4A8 100%)',
  blob: 'radial-gradient(circle,#FFD4A8 0%,transparent 70%)',
  border: 'rgba(255,212,168,.6)',
  iconBg: 'rgba(255,255,255,.7)', iconFg: '#C46A20',
  ink: '#6B3A1A', body: '#8A5A30',
  shadow: 'rgba(196,106,32,.18)'
};
const creamP = {
  bg: 'linear-gradient(135deg,#FFF4D6 0%,#FFE8B5 100%)',
  blob: 'radial-gradient(circle,#FFD75A 0%,transparent 70%)',
  border: 'rgba(255,215,90,.4)',
  iconBg: 'rgba(255,255,255,.7)', iconFg: '#A87A20',
  ink: '#5C4318', body: '#7A6030',
  shadow: 'rgba(168,122,32,.15)'
};
const lightVioletP = {
  bg: 'linear-gradient(135deg,#F0E5F8 0%,#E8DFFA 100%)',
  blob: 'radial-gradient(circle,#C8B6FF 0%,transparent 70%)',
  border: 'rgba(232,223,250,.7)',
  iconBg: 'rgba(255,255,255,.8)', iconFg: '#9070D0',
  ink: '#4A3680', body: '#6B5A9A',
  shadow: 'rgba(122,90,224,.12)'
};
const lightMintP = {
  bg: 'linear-gradient(135deg,#E5F5EE 0%,#D6F0F5 100%)',
  blob: 'radial-gradient(circle,#B5E5D6 0%,transparent 70%)',
  border: 'rgba(214,240,245,.7)',
  iconBg: 'rgba(255,255,255,.8)', iconFg: '#3A9075',
  ink: '#2A5D4A', body: '#4D7A6A',
  shadow: 'rgba(42,128,96,.12)'
};
const lightPeachP = {
  bg: 'linear-gradient(135deg,#FFF4E8 0%,#FFE8DC 100%)',
  blob: 'radial-gradient(circle,#FFD4A8 0%,transparent 70%)',
  border: 'rgba(255,232,220,.7)',
  iconBg: 'rgba(255,255,255,.8)', iconFg: '#D08550',
  ink: '#6B4520', body: '#8A6540',
  shadow: 'rgba(196,106,32,.12)'
};

// ─── Quick tile colors (small) ──────────────────────────────────────────────
const qcLight = (bg, fg, ring, shadow) => ({ bg, fg, ring, shadow });
const QC = {
  violet: qcLight('linear-gradient(140deg,#E8DFFA,#F0E5F8)', '#7A5AE0', 'rgba(200,182,255,.5)', 'rgba(122,90,224,.16)'),
  pink: qcLight('linear-gradient(140deg,#FCE0EC,#FAD0E0)', '#C4407A', 'rgba(245,184,208,.5)', 'rgba(196,64,122,.14)'),
  mint: qcLight('linear-gradient(140deg,#D6F0F5,#C5E8DC)', '#2A8060', 'rgba(181,229,214,.55)', 'rgba(42,128,96,.14)'),
  peach: qcLight('linear-gradient(140deg,#FFE8DC,#FFD8B8)', '#C46A20', 'rgba(255,212,168,.55)', 'rgba(196,106,32,.14)'),
  cream: qcLight('linear-gradient(140deg,#FFF4D6,#FFE8B5)', '#A87A20', 'rgba(255,215,90,.4)', 'rgba(168,122,32,.14)'),
  lvioletDeep: qcLight('linear-gradient(140deg,#C8B6FF,#B59AFE)', '#FFFFFF', 'rgba(200,182,255,.6)', 'rgba(122,90,224,.25)'),
  pinkDeep: qcLight('linear-gradient(140deg,#F5B8D0,#F09CC0)', '#FFFFFF', 'rgba(245,184,208,.6)', 'rgba(196,64,122,.22)'),
  mintDeep: qcLight('linear-gradient(140deg,#B5E5D6,#9AD8C2)', '#FFFFFF', 'rgba(181,229,214,.6)', 'rgba(42,128,96,.22)')
};

// ─── Avatar modal (gallery of UGC avatars) ───────────────────────────────────────
const AVATARS = [
  { id:'jayden', name:'Jayden', tag:'Lifestyle · EN',    bg:'linear-gradient(160deg,#3a2a2a 0%,#1a1414 60%)',          skin:'#9b6a4e', hair:'#1c1410', outfit:'#dcdcdc', accent:'#a02828' },
  { id:'stefan', name:'Stefan', tag:'Fitness · EN',      bg:'linear-gradient(160deg,#2f3033 0%,#1b1c1f 60%)',          skin:'#cda180', hair:'#3a2418', outfit:'#e8e3dc' },
  { id:'mei',    name:'Mei',    tag:'Beauty · EN',       bg:'linear-gradient(160deg,#d6d2c2 0%,#a59c8a 70%)',          skin:'#e0bfa2', hair:'#16110d', outfit:'#f7c4d0' },
  { id:'yuna',   name:'Yuna',   tag:'Streetwear · EN/AR',bg:'linear-gradient(160deg,#e4d6c8 0%,#bfac98 70%)',          skin:'#d6a87e', hair:'#241510', outfit:'#5c382a' },
  { id:'adriana',name:'Adriana',tag:'Editorial · EN',    bg:'linear-gradient(160deg,#e8d9c4 0%,#b59a78 70%)',          skin:'#e6c0a0', hair:'#1c1210', outfit:'#0e0c0c' },
  { id:'clara',  name:'Clara',  tag:'Vintage · EN',      bg:'linear-gradient(160deg,#c8b8a0 0%,#8e7a5e 70%)',          skin:'#f0d5b8', hair:'#b58a52', outfit:'#1a1612', accent:'#fff' },
  { id:'noor',   name:'Noor',   tag:'Skincare · AR',     bg:'linear-gradient(160deg,#b8c8c8 0%,#5e7676 70%)',          skin:'#cfa282', hair:'#0e0a08', outfit:'#a83246', accent:'#f5f0ea' },
  { id:'sofia',  name:'Sofia',  tag:'Wellness · EN/AR',  bg:'linear-gradient(160deg,#d8c6b0 0%,#a4886a 70%)',          skin:'#e8c5a0', hair:'#7a5630', outfit:'#f3e6db' },
  { id:'valentina',name:'Valentina',tag:'Fashion · EN',  bg:'linear-gradient(160deg,#d8c8b8 0%,#9e8a72 70%)',          skin:'#e8c4a0', hair:'#1c1410', outfit:'#222', accent:'#f5f5f5' },
];

// SVG portrait — stylised placeholder figure with the avatar's palette
const PortraitSVG = ({ a }) => (
  <svg viewBox="0 0 220 300" preserveAspectRatio="xMidYMax slice" style={{display:'block',width:'100%',height:'100%'}}>
    {/* room/setting */}
    <defs>
      <linearGradient id={`p-${a.id}`} x1="0" x2="0" y1="0" y2="1">
        <stop offset="0" stopColor={a.bg.match(/#[0-9a-f]{6}/gi)?.[0] || '#444'}/>
        <stop offset="1" stopColor={a.bg.match(/#[0-9a-f]{6}/gi)?.[1] || '#222'}/>
      </linearGradient>
    </defs>
    <rect width="220" height="300" fill={`url(#p-${a.id})`}/>
    {/* floor shadow */}
    <ellipse cx="110" cy="290" rx="80" ry="10" fill="rgba(0,0,0,.25)"/>
    {/* body / outfit (top) */}
    <path d={`M55 300 L60 220 Q65 175 110 175 Q155 175 160 220 L165 300 Z`} fill={a.outfit}/>
    {/* neck */}
    <rect x="100" y="150" width="20" height="32" rx="4" fill={a.skin}/>
    {/* head */}
    <ellipse cx="110" cy="122" rx="34" ry="40" fill={a.skin}/>
    {/* hair */}
    <path d={`M75 110 Q72 82 110 78 Q148 82 145 110 Q148 130 142 132 Q138 100 110 96 Q82 100 78 132 Q72 130 75 110 Z`} fill={a.hair}/>
    {/* eyes */}
    <ellipse cx="98" cy="124" rx="2.2" ry="2.8" fill="#1a0f0a"/>
    <ellipse cx="122" cy="124" rx="2.2" ry="2.8" fill="#1a0f0a"/>
    {/* lips */}
    <path d="M104 142 Q110 146 116 142" stroke="#7a3a3a" strokeWidth="1.8" fill="none" strokeLinecap="round"/>
    {/* outfit accent stripe / belt */}
    {a.accent && <rect x="68" y="232" width="84" height="6" fill={a.accent} opacity={.85}/>}
  </svg>
);

const AvatarModal = ({ selected, onSelect, onClose }) => {
  const [pending, setPending] = React.useState(selected);
  return (
    <div style={{position:'fixed',inset:0,zIndex:100,background:'rgba(60,40,90,.35)',
      backdropFilter:'blur(8px)',WebkitBackdropFilter:'blur(8px)',
      display:'flex',alignItems:'center',justifyContent:'center',padding:32,
      animation:'fadeIn .18s ease-out'}}
      onClick={onClose}>
      <div onClick={e=>e.stopPropagation()}
        style={{width:'min(960px, 100%)',maxHeight:'90vh',
          background:'linear-gradient(160deg,#F0E5F8 0%,#FCE0EC 45%,#FFE8DC 100%)',
          borderRadius:22,overflow:'hidden',display:'flex',flexDirection:'column',position:'relative',
          boxShadow:'0 40px 80px -20px rgba(122,90,224,.35), 0 0 0 1px rgba(255,255,255,.6) inset',
          color:'#1c1c1c',fontFamily:'inherit'}}>
        {/* Ambient blobs */}
        <div style={{position:'absolute',top:-120,right:-80,width:380,height:380,borderRadius:'50%',
          background:'radial-gradient(circle,#C8B6FF 0%,transparent 65%)',opacity:.55,pointerEvents:'none'}}/>
        <div style={{position:'absolute',bottom:-100,left:-80,width:340,height:340,borderRadius:'50%',
          background:'radial-gradient(circle,#FFD4A8 0%,transparent 65%)',opacity:.45,pointerEvents:'none'}}/>

        {/* Header */}
        <div style={{position:'relative',padding:'18px 22px',display:'flex',alignItems:'center',justifyContent:'space-between',
          borderBottom:'1px solid rgba(28,28,28,.08)'}}>
          <div>
            <div style={{fontFamily:'"Instrument Serif",serif',fontStyle:'italic',fontSize:24,letterSpacing:'-.01em',color:'#1c1c1c'}}>
              Choose your avatar
            </div>
            <div style={{fontSize:12,color:'#6b6377',marginTop:2}}>
              Used for UGC-style video ads · voice and accent match the avatar
            </div>
          </div>
          <button onClick={onClose} style={{width:34,height:34,borderRadius:10,border:'1px solid #E0DAE8',
            background:'#FFFFFF',color:'#4a4356',cursor:'pointer',
            display:'flex',alignItems:'center',justifyContent:'center',fontSize:18}}>×</button>
        </div>

        {/* Grid */}
        <div style={{position:'relative',padding:18,overflow:'auto'}}>
          <div style={{display:'grid',gridTemplateColumns:'repeat(5,1fr)',gap:12}}>
            {/* Create avatar tile */}
            <button style={{aspectRatio:'4/5',borderRadius:14,cursor:'pointer',
              background:'rgba(255,255,255,.55)',
              border:'1.5px dashed #C8B6FF',
              display:'flex',flexDirection:'column',alignItems:'center',justifyContent:'center',gap:14,
              color:'#7A5AE0',fontFamily:'inherit',
              transition:'background .15s, border-color .15s'}}
              onMouseEnter={e=>{e.currentTarget.style.background='rgba(255,255,255,.8)';}}
              onMouseLeave={e=>{e.currentTarget.style.background='rgba(255,255,255,.55)';}}>
              <div style={{width:54,height:54,borderRadius:14,background:'#FFFFFF',
                display:'flex',alignItems:'center',justifyContent:'center',
                boxShadow:'0 6px 16px rgba(122,90,224,.18), inset 0 0 0 1px #E0DAE8'}}>
                <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M12 5v14M5 12h14"/>
                </svg>
              </div>
              <div style={{fontSize:13,fontWeight:600,letterSpacing:'-.005em'}}>Create avatar</div>
            </button>

            {AVATARS.map(a => {
              const active = pending === a.id;
              return (
                <button key={a.id} onClick={()=>setPending(a.id)}
                  style={{aspectRatio:'4/5',borderRadius:14,cursor:'pointer',
                    border:'2px solid '+(active ? '#F5B8D0' : 'transparent'),
                    padding:0,background:'transparent',overflow:'hidden',position:'relative',
                    transition:'border-color .15s, transform .15s',
                    transform: active ? 'translateY(-2px)' : 'translateY(0)',
                    boxShadow: active ? '0 12px 28px rgba(245,184,208,.32)' : '0 4px 12px rgba(0,0,0,.2)'}}
                  onMouseEnter={e=>{ if(!active) e.currentTarget.style.transform='translateY(-2px)'; }}
                  onMouseLeave={e=>{ if(!active) e.currentTarget.style.transform='translateY(0)'; }}>
                  <PortraitSVG a={a}/>
                  {/* Pin icon (top-left) when active */}
                  {active && (
                    <div style={{position:'absolute',top:8,left:8,
                      width:24,height:24,borderRadius:24,background:'rgba(255,255,255,.92)',
                      display:'flex',alignItems:'center',justifyContent:'center',
                      boxShadow:'0 2px 6px rgba(0,0,0,.3)'}}>
                      <svg width="13" height="13" viewBox="0 0 24 24" fill="#1c1c1c">
                        <path d="M16 4l4 4-5 1-4 4-1 5-2-2-5 5-1-1 5-5-2-2 5-1 4-4z"/>
                      </svg>
                    </div>
                  )}
                  {/* Name bar */}
                  <div style={{position:'absolute',left:0,right:0,bottom:0,
                    padding: active ? '10px 10px 14px' : '10px 12px 12px',
                    background:'linear-gradient(180deg,transparent 0%,rgba(0,0,0,.55) 100%)',
                    display:'flex',alignItems:'center',justifyContent: active ? 'center' : 'flex-start'}}>
                    {active ? (
                      <div style={{padding:'9px 18px',borderRadius:999,fontSize:12.5,fontWeight:600,
                        background:'linear-gradient(120deg,#F5B8D0 0%,#F09CC0 100%)',color:'#fff',
                        boxShadow:'0 4px 12px rgba(196,64,122,.35)'}}>
                        Select avatar
                      </div>
                    ) : (
                      <div style={{fontSize:14,fontWeight:600,color:'#fff',letterSpacing:'-.005em',
                        textShadow:'0 1px 4px rgba(0,0,0,.5)'}}>{a.name}</div>
                    )}
                  </div>
                </button>
              );
            })}
          </div>
        </div>

        {/* Footer */}
        <div style={{position:'relative',padding:'14px 22px',borderTop:'1px solid rgba(28,28,28,.08)',
          background:'rgba(255,255,255,.45)',
          display:'flex',alignItems:'center',justifyContent:'space-between'}}>
          <div style={{fontSize:12,color:'#6b6377'}}>
            {AVATARS.length} avatars available · more added weekly
          </div>
          <div style={{display:'flex',gap:8}}>
            <button onClick={onClose} style={{padding:'10px 18px',borderRadius:999,
              border:'1px solid #E0DAE8',background:'#FFFFFF',
              color:'#1c1c1c',cursor:'pointer',fontFamily:'inherit',fontSize:13,fontWeight:500}}>
              Cancel
            </button>
            <button onClick={()=>{ onSelect(pending); onClose(); }}
              style={{padding:'10px 22px',borderRadius:999,border:'none',cursor:'pointer',
                fontFamily:'inherit',fontSize:13.5,fontWeight:600,color:'#1c1c1c',
                background:'linear-gradient(120deg,#C8B6FF 0%,#F5B8D0 50%,#C8B6FF 100%)',
                boxShadow:'0 6px 16px rgba(122,90,224,.32)'}}>
              Use {AVATARS.find(x=>x.id===pending)?.name || 'avatar'}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

// ─── Settings popover ──────────────────────────────────────────────────────
const SETTINGS_OPTIONS = {
  aspect: ['Auto','16:9','9:16','4:3','3:4','1:1','21:9'],
  quality: ['480p','720p','1080p','4K'],
  duration: ['Auto','5s','10s','15s']
};

const SettingsPopover = ({ values, onChange, onClose }) => {
  const Row = ({ label, hint, options, k }) => (
    <div style={{padding:'14px 16px',borderTop:'1px solid #F0EBF6'}}>
      <div style={{display:'flex',alignItems:'baseline',justifyContent:'space-between',marginBottom:9}}>
        <div style={{fontSize:12,fontWeight:600,color:'#1c1c1c',letterSpacing:'.02em'}}>{label}</div>
        {hint && <div style={{fontSize:10.5,color:'#9089A0'}}>{hint}</div>}
      </div>
      <div style={{display:'flex',flexWrap:'wrap',gap:6}}>
        {options.map(opt => {
          const active = values[k] === opt;
          return (
            <button key={opt} onClick={()=>onChange(k,opt)}
              style={{padding:'6px 11px',borderRadius:8,cursor:'pointer',fontFamily:'inherit',
                fontSize:12,fontWeight:active?600:500,
                border:'1px solid '+(active?'#1c1c1c':'#E0DAE8'),
                background: active ? '#1c1c1c' : '#FFFFFF',
                color: active ? '#FFFFFF' : '#4a4356',
                transition:'background .12s, color .12s, border-color .12s'}}>
              {opt}
            </button>
          );
        })}
      </div>
    </div>
  );
  return (
    <>
      <div onClick={onClose} style={{position:'fixed',inset:0,zIndex:40}}/>
      <div style={{position:'absolute',top:'calc(100% + 8px)',left:78,zIndex:50,
        width:300,background:'#FFFFFF',border:'1px solid #E0DAE8',borderRadius:14,
        boxShadow:'0 20px 50px -10px rgba(122,90,224,.28), 0 0 0 1px rgba(255,255,255,.5) inset',
        overflow:'hidden',fontFamily:'inherit'}}>
        <div style={{padding:'12px 16px 10px',display:'flex',alignItems:'center',justifyContent:'space-between'}}>
          <div style={{display:'flex',alignItems:'center',gap:8}}>
            <span style={{width:22,height:22,borderRadius:6,
              background:'linear-gradient(135deg,#C8B6FF,#F5B8D0)',
              display:'flex',alignItems:'center',justifyContent:'center',color:'#fff'}}>{I.sliders}</span>
            <div style={{fontSize:13,fontWeight:600,color:'#1c1c1c'}}>Output settings</div>
          </div>
          <button onClick={onClose} style={{border:'none',background:'transparent',cursor:'pointer',
            color:'#9089A0',fontSize:18,lineHeight:1,padding:4}}>×</button>
        </div>
        <Row label="Aspect ratio" k="aspect"  options={SETTINGS_OPTIONS.aspect}/>
        <Row label="Quality"      k="quality" options={SETTINGS_OPTIONS.quality}/>
        <Row label="Duration"     hint="Up to 15s" k="duration" options={SETTINGS_OPTIONS.duration}/>
      </div>
    </>
  );
};

// ─── AI input box ───────────────────────────────────────────────────────────
const AIInput = ({ glow, onAnalyze, analyzing }) => {
  const [value, setValue] = React.useState('');
  const [focused, setFocused] = React.useState(false);
  const [settingsOpen, setSettingsOpen] = React.useState(false);
  const [settings, setSettings] = React.useState({aspect:'Auto', quality:'1080p', duration:'Auto'});
  const updateSetting = (k,v) => setSettings(s => ({...s, [k]: v}));
  const [avatarOpen, setAvatarOpen] = React.useState(false);
  const [avatar, setAvatar] = React.useState('mei');
  const selectedAvatar = AVATARS.find(a => a.id === avatar) || AVATARS[0];
  const taRef = React.useRef(null);
  const autoSize = (el) => {
    if (!el) return;
    el.style.height = 'auto';
    el.style.height = Math.min(el.scrollHeight, 220) + 'px';
  };
  React.useEffect(() => autoSize(taRef.current), [value]);
  const submit = () => {
    if (!value.trim() || analyzing) return;
    onAnalyze(value.trim());
  };
  return (
    <div style={{ position: 'relative', marginTop: 18 }}>
      {glow &&
      <div style={{ position: 'absolute', inset: -3, borderRadius: 22,
        background: 'linear-gradient(120deg,#C8B6FF 0%,#F5B8D0 33%,#FFD4A8 66%,#B5E5D6 100%)',
        filter: focused ? 'blur(14px)' : 'blur(10px)',
        opacity: focused ? .85 : .55, transition: 'opacity .2s, filter .2s', pointerEvents: 'none' }} />
      }
      <div style={{ position: 'relative', background: '#FFFFFF', border: '1px solid #E0DAE8',
        borderRadius: 20, padding: '18px 20px 14px', boxShadow: '0 6px 18px rgba(122,90,224,.06)' }}>
        <textarea ref={taRef} value={value} onChange={(e) => setValue(e.target.value)}
        onFocus={() => setFocused(true)} onBlur={() => setFocused(false)}
        onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); submit(); } }}
        placeholder="Paste a product link, for example https://store.com/product, and Cavivo will analyze it..." rows={1}
        style={{ width: '100%', border: 'none', outline: 'none', fontFamily: 'inherit',
          fontSize: 15, color: '#1c1c1c', background: 'transparent',
          padding: '4px 0 14px', resize: 'none', overflow: 'auto',
          lineHeight: 1.5, minHeight: 28, maxHeight: 220 }} />
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={{ display: 'flex', gap: 6, position:'relative', alignItems:'center' }}>
            <button title={`Avatar · ${selectedAvatar.name}`} onClick={()=>setAvatarOpen(o=>!o)}
              style={{...ibtn, position:'relative', overflow:'hidden'}}>
              <span style={{width:22,height:22,borderRadius:22,background:selectedAvatar.bg,
                overflow:'hidden',display:'block',position:'relative',
                boxShadow:'inset 0 0 0 1.5px rgba(255,255,255,.6), 0 1px 3px rgba(0,0,0,.15)'}}>
                <svg viewBox="0 0 24 28" style={{position:'absolute',inset:0,width:'100%',height:'100%'}}>
                  <ellipse cx="12" cy="10" rx="4.2" ry="4.6" fill={selectedAvatar.skin}/>
                  <path d="M4 28 Q5 17 12 17 Q19 17 20 28 Z" fill={selectedAvatar.outfit}/>
                  <path d="M7.5 9 Q7 5 12 4.8 Q17 5 16.5 9 Q17 11 16 11 Q15.5 7.5 12 7.5 Q8.5 7.5 8 11 Q7 11 7.5 9 Z" fill={selectedAvatar.hair}/>
                </svg>
              </span>
            </button>
            {avatarOpen && <AvatarModal selected={avatar} onSelect={setAvatar} onClose={()=>setAvatarOpen(false)}/>}
            <button title="Attach" style={ibtn}><span style={{ color: '#6b6377' }}>{I.attach}</span></button>
            <button title="Output settings" onClick={()=>setSettingsOpen(o=>!o)}
              style={{...ibtn, background: settingsOpen ? '#F0E5F8' : 'transparent'}}>
              <span style={{ color: settingsOpen ? '#7A5AE0' : '#6b6377' }}>{I.sliders}</span>
            </button>
            {settingsOpen && <SettingsPopover values={settings} onChange={updateSetting} onClose={()=>setSettingsOpen(false)}/>}
          </div>
          <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
            <span style={{ fontSize: 11, color: '#9089A0' }}>{analyzing ? 'Analyzing link...' : 'GPT + Seedance'}</span>
            <button title="Voice" style={{ ...ibtn, width: 36, height: 36 }}><span style={{ color: '#6b6377' }}>{I.mic}</span></button>
            <button title="Send" onClick={submit} disabled={!value || analyzing}
            style={{ width: 36, height: 36, borderRadius: 10, border: 'none', cursor: value && !analyzing ? 'pointer' : 'default',
              color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center',
              background: value && !analyzing ?
              'linear-gradient(135deg,#C8B6FF 0%,#F5B8D0 50%,#C8B6FF 100%)' :
              'linear-gradient(135deg,#E8DFFA 0%,#F0E5F8 100%)',
              boxShadow: value && !analyzing ? '0 4px 12px rgba(122,90,224,.3)' : 'none',
              opacity: value ? 1 : .65, transition: 'opacity .15s' }}>{I.send}</button>
          </div>
        </div>
      </div>
    </div>);

};
const ibtn = { width: 30, height: 30, borderRadius: 8, border: 'none', background: 'transparent', cursor: 'pointer',
  display: 'flex', alignItems: 'center', justifyContent: 'center' };

// ─── Generated ad workspace ────────────────────────────────────────────────
const MiniPhonePreview = ({ title, tag, cta = 'Shop now', gradient, accent, lift = 0, active = false }) => (
  <div style={{ width: active ? 232 : 132, height: active ? 470 : 270, borderRadius: active ? 40 : 28, padding: active ? 10 : 7,
    background: 'linear-gradient(160deg,#2a1f3d 0%,#1c1c1c 100%)',
    boxShadow: active ? '0 34px 70px -22px rgba(60,30,80,.55)' : '0 24px 44px -18px rgba(60,30,80,.45)',
    transform: `translateY(${lift}px)`, flexShrink: 0 }}>
    <div style={{ width: '100%', height: '100%', borderRadius: active ? 30 : 22, overflow: 'hidden',
      position: 'relative', background: gradient }}>
      <div style={{ position: 'absolute', top: active ? 9 : 7, left: '50%', transform: 'translateX(-50%)',
        width: active ? 64 : 48, height: active ? 14 : 11, borderRadius: 10, background: '#1c1c1c', zIndex: 3 }} />
      <div style={{ position: 'absolute', inset: 0,
        background: active ?
        'linear-gradient(180deg,rgba(28,28,28,.02) 0%,rgba(28,28,28,.08) 45%,rgba(28,28,28,.38) 100%)' :
        'transparent' }} />
      <div style={{ position: 'absolute', top: active ? 50 : 42, left: active ? 18 : 12, right: active ? 18 : 'auto',
        display: 'flex', alignItems: 'center', justifyContent: active ? 'space-between' : 'flex-start', gap: 8 }}>
        <span style={{ padding: active ? '6px 10px' : '4px 7px',
          background: 'rgba(0,0,0,.34)', borderRadius: 999, color: '#fff',
          fontSize: active ? 10.5 : 8.5, fontWeight: 800, letterSpacing: '.04em' }}>{tag}</span>
        {active && <span style={{ padding: '6px 9px', background: 'rgba(255,255,255,.22)',
          borderRadius: 999, color: '#fff', fontSize: 10, fontWeight: 700 }}>00:15</span>}
      </div>
      <div style={{ position: 'absolute', top: active ? 92 : 78, left: active ? 22 : '50%',
        transform: active ? 'none' : 'translateX(-50%)',
        width: active ? 150 : 78, height: active ? 176 : 78, borderRadius: active ? 28 : 18,
        background: active ? 'rgba(255,255,255,.55)' : 'rgba(255,255,255,.84)',
        boxShadow: '0 18px 38px rgba(0,0,0,.18)',
        backdropFilter: active ? 'blur(8px)' : 'none' }} />
      {active && <div style={{ position: 'absolute', top: 128, right: 22, width: 62,
        display: 'flex', flexDirection: 'column', gap: 8 }}>
        {['Hook', 'Scene', 'CTA'].map((x, i) => (
          <span key={i} style={{ height: 22, borderRadius: 999,
            background: 'rgba(255,255,255,.64)', color: '#4A3680',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 8.5, fontWeight: 800 }}>{x}</span>
        ))}
      </div>}
      <div style={{ position: 'absolute', inset: 0, display: active ? 'flex' : 'none',
        alignItems: 'center', justifyContent: 'center', pointerEvents: 'none' }}>
        <div style={{ marginTop: 18, width: 58, height: 58, borderRadius: 58,
          background: 'rgba(28,28,28,.72)', color: '#fff', display: 'flex',
          alignItems: 'center', justifyContent: 'center',
          boxShadow: '0 8px 22px rgba(0,0,0,.25)' }}>{I.play || I.send}</div>
      </div>
      <div style={{ position: 'absolute', left: active ? 22 : 13, right: active ? 22 : 13, bottom: active ? 86 : 54, color: '#fff',
        fontSize: active ? 29 : 18, lineHeight: 1.04, fontWeight: 800,
        textShadow: '0 2px 12px rgba(0,0,0,.35)' }}>{title}</div>
      <div style={{ position: 'absolute', left: active ? 20 : 12, right: active ? 20 : 12, bottom: active ? 22 : 14,
        background: '#fff', borderRadius: active ? 13 : 10, padding: active ? '10px 12px' : '8px 9px',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        fontSize: active ? 12 : 9.5, color: '#1c1c1c', fontWeight: 700 }}>
        <span>{cta}</span>
        <span style={{ width: active ? 28 : 18, height: active ? 28 : 18, borderRadius: 28, background: accent,
          color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{I.play || I.send}</span>
      </div>
    </div>
  </div>
);

const EditableCopyBlock = ({ label, children, minHeight = 72 }) => {
  const text = String(children).replace(/\\n/g, '\n').trim();
  return (
    <div>
      <div style={{ fontSize: 11, fontWeight: 700, color: '#9089A0',
        letterSpacing: '.08em', textTransform: 'uppercase', marginBottom: 7 }}>{label}</div>
      <textarea key={text} defaultValue={text} style={{ width: '100%', minHeight, resize: 'vertical',
        border: '1px solid #E0DAE8', borderRadius: 12, padding: '11px 12px',
        background: '#FFFFFF', color: '#3b3148', fontFamily: 'inherit',
        fontSize: 13, lineHeight: 1.48, outline: 'none' }} />
    </div>
  );
};

const GeneratedAdWorkspace = ({ result, analyzing, error }) => (
  <section style={{ marginTop: 34 }}>
    <div style={{ display: 'flex', alignItems: 'center', gap: 12, margin: '0 0 16px' }}>
      <div style={{ flex: 1, height: 1, background: '#E0DAE8' }} />
      <div style={{ fontSize: 12.5, color: '#6b6377', letterSpacing: '.02em' }}>
        {analyzing ? 'Analyzing product link with GPT...' : 'Product link analyzed - review, edit and generate'}
      </div>
      <div style={{ flex: 1, height: 1, background: '#E0DAE8' }} />
    </div>

    <div style={{ display: 'grid', gridTemplateColumns: '.95fr 1.05fr', gap: 18,
      background: 'rgba(255,255,255,.72)', border: '1px solid #E0DAE8',
      borderRadius: 22, padding: 18, boxShadow: '0 18px 45px -30px rgba(122,90,224,.45)' }}>
      <div style={{ position: 'relative', minHeight: 430, borderRadius: 18, overflow: 'hidden',
        background: 'linear-gradient(160deg,#F0E5F8 0%,#FCE0EC 48%,#FFE8DC 100%)',
        display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 22 }}>
        <div style={{ position: 'absolute', top: -70, right: -50, width: 220, height: 220,
          borderRadius: '50%', background: 'radial-gradient(circle,#C8B6FF 0%,transparent 68%)',
          opacity: .7 }} />
        <div style={{ position: 'absolute', top: 18, left: 18, zIndex: 2, display: 'inline-flex',
          alignItems: 'center', gap: 7, padding: '6px 10px',
          background: 'rgba(255,255,255,.82)', border: '1px solid rgba(255,255,255,.65)',
          borderRadius: 999, color: '#7A5AE0', fontSize: 11, fontWeight: 700 }}>
          {I.phone} Render preview
        </div>
        <div style={{ position: 'absolute', bottom: 18, left: 18, right: 18, zIndex: 2,
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          padding: '10px 12px', borderRadius: 14, background: 'rgba(255,255,255,.84)',
          border: '1px solid rgba(255,255,255,.72)', color: '#4a4356',
          fontSize: 12.5, fontWeight: 600 }}>
          <span>{analyzing ? 'Waiting for GPT analysis...' : error || result.status || 'Video appears here after generation'}</span>
          <span style={{ color: '#7A5AE0' }}>9:16 preview</span>
        </div>
        <div style={{ position: 'relative', display: 'flex', alignItems: 'center',
          justifyContent: 'center' }}>
          <MiniPhonePreview title={result.videoTitle} tag={analyzing ? 'ANALYZING' : 'GENERATED VIDEO'} cta={result.cta} accent="#7A5AE0" active
            gradient="linear-gradient(180deg,#C8B6FF 0%,#F5B8D0 65%,#FFD4A8 100%)" />
        </div>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 14 }}>
          <div>
            <div style={{ display: 'inline-flex', alignItems: 'center', gap: 7, padding: '5px 9px',
              background: '#E8DFFA', color: '#7A5AE0', borderRadius: 999,
              fontSize: 11, fontWeight: 700 }}>{I.bot} GPT draft</div>
            <h2 style={{ margin: '11px 0 4px', fontSize: 24, lineHeight: 1.12,
              letterSpacing: '-.02em', color: '#1c1c1c' }}>Script and ad copy</h2>
            <p style={{ margin: 0, color: '#6b6377', fontSize: 13.5, lineHeight: 1.5 }}>
              Edit the generated copy before sending the approved version to Seedance.
            </p>
          </div>
          <button style={{ flexShrink: 0, padding: '10px 14px', borderRadius: 999,
            border: '1px solid #E0DAE8', background: '#fff', cursor: 'pointer',
            color: '#4a4356', fontFamily: 'inherit', fontWeight: 700, fontSize: 12.5 }}>
            Save edits
          </button>
        </div>

        <EditableCopyBlock label="Hook">
          {result.hook}
        </EditableCopyBlock>
        <EditableCopyBlock label="15s Script" minHeight={112}>
          {result.script}
        </EditableCopyBlock>
        <EditableCopyBlock label="Ad Copy">
          {result.adCopy}
        </EditableCopyBlock>
        <EditableCopyBlock label="Seedance Prompt" minHeight={92}>
          {result.seedancePrompt}
        </EditableCopyBlock>

        <div style={{ display: 'flex', gap: 10, alignItems: 'center', justifyContent: 'space-between',
          paddingTop: 2 }}>
          <div style={{ fontSize: 12.5, color: '#9089A0' }}>
            3 variations ready · 9:16 · 1080p
          </div>
          <button style={{ display: 'inline-flex', alignItems: 'center', gap: 9,
            padding: '13px 20px', borderRadius: 999, border: 'none', cursor: 'pointer',
            fontFamily: 'inherit', fontWeight: 800, color: '#1c1c1c',
            background: 'linear-gradient(120deg,#C8B6FF 0%,#F5B8D0 50%,#FFD4A8 100%)',
            boxShadow: '0 10px 24px rgba(122,90,224,.24)' }}>
            Generate with Seedance {I.send}
          </button>
        </div>
      </div>
    </div>
  </section>
);

const DEFAULT_ANALYSIS = {
  hook: 'People with dull skin are switching to Glowwell because it looks fresher in three days.',
  script: 'Scene 1: Creator holds product close to camera and says, "I almost skipped this serum."\\nScene 2: Show texture, application and quick before/after glow.\\nScene 3: End on product packshot with clear CTA: "Try Glowwell today."',
  adCopy: 'Your fastest glow-up step. Lightweight serum, soft finish, daily routine friendly. Shop Glowwell and test the 3-day glow challenge.',
  seedancePrompt: 'Vertical 9:16 UGC skincare ad, warm bathroom light, creator holding serum, close-up texture shots, smooth handheld movement, soft pastel palette, fast captions, product packshot ending.',
  videoTitle: 'Glow in 3 days',
  cta: 'Shop now',
  status: 'Video appears here after generation'
};

// ─── Main view ──────────────────────────────────────────────────────────────
function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const auth = useSupabaseAuth();
  const [authOpen, setAuthOpen] = React.useState(
    () => new URLSearchParams(window.location.search).get('login') === '1'
  );
  const [active, setActive] = React.useState('sidekick');
  const [analysis, setAnalysis] = React.useState(DEFAULT_ANALYSIS);
  const [analyzing, setAnalyzing] = React.useState(false);
  const [analysisError, setAnalysisError] = React.useState('');

  const displayName = auth.user?.user_metadata?.full_name
    || auth.user?.user_metadata?.name
    || auth.user?.email?.split('@')[0]
    || 'Mira';

  const analyzeProduct = async (url) => {
    setAnalyzing(true);
    setAnalysisError('');
    try {
      const callAnalyze = async (endpoint) => {
        const response = await fetch(endpoint, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ url })
        });
        const data = await response.json();
        if (!response.ok) throw new Error(data.error || 'Could not analyze this product link.');
        return data;
      };
      let data;
      try {
        data = await callAnalyze('/api/analyze');
      } catch (localError) {
        throw localError;
      }
      setAnalysis({ ...DEFAULT_ANALYSIS, ...data });
    } catch (error) {
      setAnalysisError(error.message || 'Could not analyze this product link.');
      setAnalysis({
        ...DEFAULT_ANALYSIS,
        status: 'Local API is not running yet. Start cavivo_server.py to use GPT analysis.'
      });
    } finally {
      setAnalyzing(false);
    }
  };

  const greetingFont = t.greetingStyle === 'serif-italic' ?
  '"Instrument Serif", "Fraunces", serif' :
  'inherit';
  const greetingStyle = t.greetingStyle === 'serif-italic' ? 'italic' : 'normal';

  const dens = t.starterDensity;
  const cardMinH = dens === 'compact' ? 130 : dens === 'comfy' ? 180 : 158;

  return (
    <div style={{ display: 'flex', height: '100vh', background: '#FAF7FE',
      fontFamily: '"Inter","SF Pro Text",ui-sans-serif,system-ui,sans-serif', color: '#1c1c1c' }}>

      <Sidebar active={active} setActive={setActive} />

      <main style={{ flex: 1, display: 'flex', flexDirection: 'column', position: 'relative', overflow: 'hidden' }}>

        {/* Ambient background blobs */}
        {t.showAmbientBlobs &&
        <>
            <div style={{ position: 'absolute', top: -120, right: -80, width: 380, height: 380, borderRadius: '50%',
            background: 'radial-gradient(circle,#E8DFFA 0%,transparent 65%)', pointerEvents: 'none' }} />
            <div style={{ position: 'absolute', top: 60, left: '40%', width: 300, height: 300, borderRadius: '50%',
            background: 'radial-gradient(circle,#FCE0EC 0%,transparent 65%)', pointerEvents: 'none', opacity: .7 }} />
            <div style={{ position: 'absolute', top: -40, right: '30%', width: 260, height: 260, borderRadius: '50%',
            background: 'radial-gradient(circle,#FFE8DC 0%,transparent 65%)', pointerEvents: 'none', opacity: .6 }} />
          </>
        }

        <div style={{ position: 'relative', zIndex: 1 }}>
          <TopBar
            user={auth.user}
            onSignIn={() => setAuthOpen(true)}
            onSignOut={() => auth.signOut()}
          />
        </div>
        <AuthModal open={authOpen} onClose={() => setAuthOpen(false)} auth={auth} />

        <div style={{ flex: 1, overflow: 'auto', position: 'relative', zIndex: 1 }}>
          <div style={{ maxWidth: 980, margin: '0 auto', padding: '40px 32px 40px' }}>
            {/* Greeting */}
            <div style={{ textAlign: 'center', marginBottom: 28 }}>
              <h1 style={{ margin: 0, fontSize: 38, fontWeight: 500, letterSpacing: '-.02em',
                fontFamily: greetingFont, fontStyle: greetingStyle, color: '#1c1c1c' }}>
                Good morning,{' '}
                <span style={{ background: 'linear-gradient(120deg,#9070D0 0%,#C4407A 50%,#D08550 100%)',
                  WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent',
                  backgroundClip: 'text' }}>{displayName}</span>
              </h1>
              <p style={{ margin: '10px 0 0', fontSize: 14.5, color: '#6b6377' }}>
                Paste a product link to analyze, script and generate your next video ad.
              </p>
            </div>

            {/* Quick tiles row */}
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(8,1fr)', gap: 8, marginBottom: 0 }}>
              <QuickTile icon={I.attach} label="Paste link" color={QC.lvioletDeep} href="/" />
              <QuickTile icon={I.search} label="Analyze page" color={QC.pinkDeep} />
              <QuickTile icon={I.doc} label="Product brief" color={QC.mintDeep} />
              <QuickTile icon={I.pen} label="Ad copy" color={QC.peach} />
              <QuickTile icon={I.spark} label="Script angles" color={QC.mint} />
              <QuickTile icon={I.bot} label="Seedance" color={QC.violet} />
              <QuickTile icon={I.phone} label="9:16 videos" color={QC.pink} />
              <QuickTile icon={I.chart} label="Test pack" color={QC.cream} />
            </div>

            {/* AI input */}
            <AIInput glow={t.inputGlow} onAnalyze={analyzeProduct} analyzing={analyzing} />

            <GeneratedAdWorkspace result={analysis} analyzing={analyzing} error={analysisError} />

            <div style={{ height: 40 }} />
          </div>
        </div>
      </main>

      <TweaksPanel title="Tweaks">
        <TweakSection label="Greeting" />
        <TweakRadio label="Style" value={t.greetingStyle}
        options={['serif-italic', 'sans']}
        onChange={(v) => setTweak('greetingStyle', v)} />
        <TweakSection label="Atmosphere" />
        <TweakToggle label="Ambient blobs" value={t.showAmbientBlobs}
        onChange={(v) => setTweak('showAmbientBlobs', v)} />
        <TweakToggle label="AI input glow" value={t.inputGlow}
        onChange={(v) => setTweak('inputGlow', v)} />
        <TweakSection label="Starter cards" />
        <TweakRadio label="Density" value={t.starterDensity}
        options={['compact', 'regular', 'comfy']}
        onChange={(v) => setTweak('starterDensity', v)} />
      </TweaksPanel>
    </div>);

}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
