// ─── Constants ────────────────────────────────────────────────────────────────

const ROLES        = { SUPER_ADMIN: 'super_admin' };
const CURRENT_ROLE = ROLES.SUPER_ADMIN;

const PAGE_TITLES = {
  dashboard: 'Dashboard',
  requests:  'Requests',
  bookings:  'Bookings',
  blog:      'Blog',
  signwall:  'Sign Wall',
  content:   'Content',
  legal:     'Legal',
  users:     'Users',
  settings:  'Settings',
};

// ─── i18n seed helper ─────────────────────────────────────────────────────────

const t = (en, fr = '', darija = '') => ({ en, fr, darija });

// ─── CMS seed (fallback when Supabase has no content rows yet) ────────────────

const INIT_CONTENT = {
  brand: {
    logoLight:       'assets/logo-mark.png',
    logoDark:        'assets/logo-mark-white.png',
    favicon:         '',
    siteTitle:       t('Blan Studio — Your Creative Partner'),
    metaDescription: t('High-quality branding, web, and product design delivered through a simple monthly subscription. No delays, no hiring, no wasted time.'),
    ogImage:         '',
    name:            'Blan Studio',
    email:           'contact.benadra@gmail.com',
    phone:           '',
    location:        '',
    ctaLabel:        t('Book a Call',   'Réserver un appel', 'حجز مكالمة'),
    loginLabel:      t('Login',         'Connexion',         'دخول'),
  },
  hero: {
    eyebrow:      t('Your Creative Partner', 'Votre Partenaire Créatif', 'شريككم الإبداعي'),
    title:        t('Design That Moves Your Business Forward', 'Un Design Qui Propulse Votre Business', ''),
    subtitle:     t('High-quality branding, web, and product design delivered through a simple monthly subscription. No delays, no hiring, no wasted time.', '', ''),
    ctaPrimary:   { label: t('Explore Services', 'Explorer les Services', 'استكشف الخدمات'), linkType: 'internal', section: 'services', url: '', newTab: false },
    ctaSecondary: { label: t('View Pricing Plans', 'Voir les Tarifs', 'شوف الأسعار'),        linkType: 'internal', section: 'pricing',  url: '', newTab: false },
  },
  services: [
    { id: '1', title: t('Branding', 'Branding', 'البراندينغ'),        desc: t('', '', ''), tags: t('Logo design, Typography, Color system, Brand guidelines, Business cards, Brand identity', '', ''), cardType: 'carousel', mediaImage: '', mediaImages: ['assets/services/branding 1.jpg', 'assets/services/branding 2.jpg', 'assets/services/branding 3.jpg'], mediaSrc: '' },
    { id: '2', title: t('Web & Product', 'Web & Produit', ''),         desc: t('', '', ''), tags: t('Landing pages, SaaS UI, Design systems, Component libraries, UX audit, Prototyping', '', ''),    cardType: 'carousel', mediaImage: '', mediaImages: ['assets/services/web and product 1.avif', 'assets/services/web and product 2.avif', 'assets/services/web and product 3.avif'], mediaSrc: '' },
    { id: '3', title: t('Graphic Design', 'Design Graphique', ''),     desc: t('', '', ''), tags: t('Marketing materials, Presentations, Social assets, Print design, Infographics, Packaging', '', ''), cardType: 'carousel', mediaImage: '', mediaImages: ['assets/services/graphic design 1.jpg', 'assets/services/graphic design 2.jpg', 'assets/services/graphic design 3.jpg'], mediaSrc: '' },
    { id: '4', title: t('Motion', 'Motion', ''),                       desc: t('', '', ''), tags: t('Micro-interactions, Animated assets, Video graphics, UI animations, Loading states', '', ''),      cardType: 'video',    mediaImage: '', mediaImages: [], mediaSrc: 'assets/services/motion.mp4' },
    { id: '5', title: t('Strategy', 'Stratégie', ''),                  desc: t('', '', ''), tags: t('Brand positioning, UX strategy, Design direction, Competitive audit, Roadmapping', '', ''),        cardType: 'carousel', mediaImage: '', mediaImages: ['assets/services/strategy 1.jpg', 'assets/services/strategy 2.jpg'], mediaSrc: '' },
    { id: '6', title: t('& More', '& Plus', ''),                       desc: t('Additional support across formats, channels, and disciplines — wherever the work takes us.', '', ''), tags: t('3D & Illustration, Print Design, Email Templates, Pitch Decks, Iconography, UI Audits, Copywriting, Infographics', '', ''), cardType: 'text', mediaImage: '', mediaImages: [], mediaSrc: '' },
  ],
  about: {
    headline: t('We Remove the Friction that slow your brand down.', '', ''),
    testimonial: {
      quote:  t("Blan turned a chaotic backlog into a shipped product in six weeks. Best design decision we've made — and we didn't have to hire anyone.", '', ''),
      name:   'Elena Russo',
      role:   t('CEO, Meridian AI', '', ''),
      avatar: 'assets/reviews/testimonials-1.jpg',
    },
    painPoints: [
      { id: '1', muted: t('Forget about', '', ''), bold: t('unreliable freelancers who ghost you', '', '') },
      { id: '2', muted: t('No more', '', ''),      bold: t('agencies with bloated timelines', '', '') },
      { id: '3', muted: t('Stop', '', ''),          bold: t('juggling briefs across scattered tools', '', '') },
      { id: '4', muted: t('Say bye to', '', ''),    bold: t('slow, expensive in-house design costs', '', '') },
      { id: '5', muted: t('Skip', '', ''),          bold: t('the month-long agency onboarding', '', '') },
      { id: '6', muted: t('Done with', '', ''),     bold: t('waiting weeks for a single deliverable', '', '') },
    ],
    stats: [
      { id: '1', target: 70, suffix: '%', label: t('lower cost vs agencies and in-house teams', '', '') },
      { id: '2', target: 40, suffix: '%', label: t('faster turnaround on every request', '', '') },
      { id: '3', target: 60, suffix: '%', label: t('fewer revisions — powered by senior designers', '', '') },
    ],
  },
  reviews: [
    { id: '1', name: 'Elena Russo',   role: t('CEO', '', ''),            company: 'Meridian AI',   avatar: 'assets/reviews/testimonials-1.jpg', quote: t("From a rough brief to a deployed product in six weeks. Genuinely the best outside team we've worked with.", '', ''), featured: false, video: '', media: '' },
    { id: '2', name: 'Marcus Obi',    role: t('VP Product', '', ''),     company: 'Helix Systems', avatar: 'assets/reviews/testimonials-5.jpg', quote: t("We went from nothing to a production AI copilot in 7 weeks — design, evals, and infrastructure fully handled.", '', ''), featured: true, video: 'assets/reviews/testimonial featured video.mp4', media: '' },
    { id: '3', name: 'Sara Kim',      role: t('Staff Engineer', '', ''), company: 'Rayfield',      avatar: 'assets/reviews/testimonials-3.jpg', quote: t("Eval-first engineering gave us real confidence before shipping. Latency under 300ms p95 from day one.", '', ''), featured: false, video: '', media: '' },
    { id: '4', name: 'Julien Moreau', role: t('CPO', '', ''),            company: 'Stackfield',    avatar: 'assets/reviews/testimonials-4.jpg', quote: t("The hand-off was the cleanest I've seen — CI, evals, and docs all ready. Zero ramp-up for our engineers.", '', ''), featured: false, video: '', media: '' },
  ],
  process: [
    { id: '1', title: t('Join Blan', '', ''),            desc: t('Start by booking a call or subscribing. Whatever works best for you.', '', ''),                       cta: { label: t('View Plans', '', ''),       linkType: 'internal', section: 'pricing', url: '', newTab: false }, label: t('Choose your plan', '', '') },
    { id: '2', title: t('Submit Tasks', '', ''),          desc: t('Send in any request — text, video, or files. It takes just minutes to get started.', '', ''),        cta: { label: t('Submit Now', '', ''),       linkType: 'internal', section: 'contact', url: '', newTab: false }, label: t('New task', '', '') },
    { id: '3', title: t('Get Matched', '', ''),           desc: t('Tasks are assigned to vetted experts based on the project scope and skillset required.', '', ''),    cta: { label: t('View All Talents', '', ''), linkType: 'internal', section: 'about',   url: '', newTab: false }, label: t('Pick your expert', '', '') },
    { id: '4', title: t('Refine Until Perfect', '', ''),  desc: t('Receive updates every business day. Refine with unlimited revisions until everything clicks.', '', ''), cta: { label: t('Get Started', '', ''),      linkType: 'internal', section: 'contact', url: '', newTab: false }, label: t('Revision thread', '', '') },
  ],
  works: [
    { id: '1', title: t('Helix AI Dashboard', '', ''),      tags: t('Product Design, AI/ML', '', ''),         img: 'assets/our work/work 1.png', href: '#' },
    { id: '2', title: t('Meridian Brand Identity', '', ''), tags: t('Branding, Visual Identity', '', ''),     img: 'assets/our work/work 2.png', href: '#' },
    { id: '3', title: t('Forma SaaS Platform', '', ''),     tags: t('UI Design, SaaS', '', ''),               img: 'assets/our work/work 3.png', href: '#' },
    { id: '4', title: t('Caspian Web Redesign', '', ''),    tags: t('Web Design, Conversion', '', ''),        img: 'assets/our work/work 4.png', href: '#' },
    { id: '5', title: t('Orbis Motion System', '', ''),     tags: t('Motion, Design System', '', ''),         img: 'assets/our work/work 5.png', href: '#' },
    { id: '6', title: t('Stackfield App UI', '', ''),       tags: t('Mobile UI, Product', '', ''),            img: 'assets/our work/work 6.png', href: '#' },
    { id: '7', title: t('Rayfield Marketing', '', ''),      tags: t('Marketing, Landing Page', '', ''),       img: 'assets/our work/work 7.png', href: '#' },
  ],
  pricing: [
    {
      id: '1', tier: 'Standard', tag: t('', '', ''),
      blurb: t('For steady, ongoing design needs', '', ''),
      prices: { monthly: 4499, quarter: 3999, annual: 2999 },
      features: t('1 active task at a time\nAverage delivery: 48–72 hours\nUnlimited requests\nAll core design services included\nPause or resume anytime', '', ''),
      note: t('Best for startups and small teams', '', ''),
      cta: { label: t('Get Started', '', ''), linkType: 'internal', section: 'contact', url: '', newTab: false },
    },
    {
      id: '2', tier: 'Pro', tag: t('Most Popular', '', ''),
      blurb: t('For fast-moving teams that need priority execution', '', ''),
      prices: { monthly: 6999, quarter: 5499, annual: 4499 },
      features: t('2 active tasks at a time\nAverage delivery: 24–48 hours\nPriority queue\nUnlimited requests\nAll core design services included\nPause or resume anytime', '', ''),
      note: t('Best for scaling teams and agencies', '', ''),
      cta: { label: t('Get Started', '', ''), linkType: 'internal', section: 'contact', url: '', newTab: false },
    },
  ],
  faq: [
    { id: '1', question: t('How fast can we start a sprint?', '', ''),           answer: t('Most engagements kick off within 7 business days of a signed SOW. Discovery calls in the same week.', '', '') },
    { id: '2', question: t('Do you work with our existing engineers?', '', ''),   answer: t('Yes — pods are designed to embed. We pair with your team in your repo, your stack, and your standups.', '', '') },
    { id: '3', question: t('Which models and providers do you support?', '', ''),  answer: t('OpenAI, Anthropic, Google, open-weight Llama / Qwen / Mistral, and on-prem deployments via vLLM or Ollama.', '', '') },
    { id: '4', question: t('Can you sign our enterprise paperwork?', '', ''),      answer: t('MSAs, DPAs, BAAs, SOC 2 Type II, and custom security review questionnaires — yes to all.', '', '') },
    { id: '5', question: t('What happens after a sprint ends?', '', ''),           answer: t('You own the code, the evals, and the deployment. We offer optional retainers for monitoring and iteration.', '', '') },
  ],

  partners: [
    { id: '1', logo: 'assets/partners/partner-1.png', url: '#' },
    { id: '2', logo: 'assets/partners/partner-2.png', url: '#' },
    { id: '3', logo: 'assets/partners/partner-3.png', url: '#' },
    { id: '4', logo: 'assets/partners/partner-4.png', url: '#' },
    { id: '5', logo: 'assets/partners/partner-5.png', url: '#' },
    { id: '6', logo: 'assets/partners/partner-6.png', url: '#' },
    { id: '7', logo: 'assets/partners/partner-7.png', url: '#' },
    { id: '8', logo: 'assets/partners/partner-8.png', url: '#' },
  ],
};

const INIT_LEGAL = [
  { slug: 'privacy-policy', content_json: { title: t('Privacy Policy', 'Politique de Confidentialité', 'سياسة الخصوصية'), content: t('', '', '') } },
  { slug: 'terms',          content_json: { title: t('Terms of Service', "Conditions d'Utilisation", 'شروط الخدمة'),      content: t('', '', '') } },
];

const genId = () => String(Date.now() + Math.random());

// ─── App ──────────────────────────────────────────────────────────────────────

function App() {
  // ── Auth state ────────────────────────────────────────────────────────────
  const [session,     setSession]     = React.useState(null);
  const [authLoading, setAuthLoading] = React.useState(true);

  // ── Admin state ───────────────────────────────────────────────────────────
  const [page,       setPage]       = React.useState('dashboard');
  const [lang,       setLang]       = React.useState('en');
  const [loading,    setLoading]    = React.useState(false);
  const [requests,   _setRequests]  = React.useState([]);
  const [bookings,   setBookings]   = React.useState([]);
  const [signWall,   setSignWall]   = React.useState([]);
  const [content,    _setContent]   = React.useState(INIT_CONTENT);
  const [legalPages, setLegalPages] = React.useState(INIT_LEGAL);

  const contentRef  = React.useRef(INIT_CONTENT);
  const requestsRef = React.useRef([]);

  const setContent = (updater) => {
    _setContent(prev => {
      const next = typeof updater === 'function' ? updater(prev) : updater;
      contentRef.current = next;
      return next;
    });
  };

  const setRequests = (updater) => {
    _setRequests(prev => {
      const next = typeof updater === 'function' ? updater(prev) : updater;
      requestsRef.current = next;
      return next;
    });
  };

  // ── Auth bootstrap ────────────────────────────────────────────────────────

  React.useEffect(() => {
    // Check persisted session on load
    db.auth.getSession().then(({ data: { session } }) => {
      setSession(session);
      setAuthLoading(false);
      if (session) loadAll();
    });

    // React to sign-in / sign-out events
    const { data: { subscription } } = db.auth.onAuthStateChange((event, session) => {
      setSession(session);
      // SIGNED_IN fires on token refresh (tab focus) — refresh data silently so no spinner unmounts active pages
      if (event === 'SIGNED_IN')  loadAll(true);
      if (event === 'SIGNED_OUT') {
        setRequests([]);
        setBookings([]);
        setSignWall([]);
      }
    });

    return () => subscription.unsubscribe();
  }, []);

  const handleSignOut = async () => {
    await db.auth.signOut();
  };

  // ── Data loading ──────────────────────────────────────────────────────────

  const loadAll = async (silent = false) => {
    if (!silent) setLoading(true);
    try {
      const [sectionsRes, requestsRes, legalRes, signWallRes, bookingsRes] = await Promise.all([
        db.from('content_sections').select('section_name, content_json'),
        db.from('requests').select('*').order('created_at', { ascending: false }),
        db.from('legal_pages').select('*').order('updated_at', { ascending: false }),
        db.from('sign_wall_items').select('*').order('created_at', { ascending: false }),
        db.from('bookings').select('*').order('created_at', { ascending: false }),
      ]);

      if (!sectionsRes.error && sectionsRes.data?.length) {
        const map    = Object.fromEntries(sectionsRes.data.map(r => [r.section_name, r.content_json]));
        const merged = {};
        Object.keys(INIT_CONTENT).forEach(k => { merged[k] = map[k] || INIT_CONTENT[k]; });
        setContent(merged);
      }

      if (!requestsRes.error) setRequests(requestsRes.data  || []);
      if (!legalRes.error && legalRes.data?.length) setLegalPages(legalRes.data);
      if (!signWallRes.error) setSignWall(signWallRes.data  || []);
      if (!bookingsRes.error) setBookings(bookingsRes.data  || []);
    } catch (e) {
      console.warn('[app] load failed', e);
    } finally {
      if (!silent) setLoading(false);
    }
  };

  // ── Request handlers ──────────────────────────────────────────────────────

  const handleStatusChange = async (id, status) => {
    setRequests(prev => prev.map(r => r.id === id ? { ...r, status, updated_at: new Date().toISOString() } : r));
    await db.from('requests').update({ status, updated_at: new Date().toISOString() }).eq('id', id);
  };

  // ── Sign wall handlers ────────────────────────────────────────────────────

  const handleHideSignWall = async (id) => {
    setSignWall(prev => prev.map(i => i.id === id ? { ...i, is_hidden: true } : i));
    await db.from('sign_wall_items').update({ is_hidden: true }).eq('id', id);
  };

  // ── Legal handlers ────────────────────────────────────────────────────────

  const handleLegalSave = async (slug, contentJson) => {
    const { error } = await db.from('legal_pages')
      .upsert({ slug, content_json: contentJson }, { onConflict: 'slug' });
    if (error) { console.error('[legal] save failed', error); return; }
    setLegalPages(prev => {
      const exists = prev.find(p => p.slug === slug);
      return exists
        ? prev.map(p => p.slug === slug ? { ...p, content_json: contentJson } : p)
        : [...prev, { slug, content_json: contentJson }];
    });
  };

  // ── Content handlers ──────────────────────────────────────────────────────

  const makeListHandlers = (key) => ({
    add: (item) => {
      const newList = [...contentRef.current[key], { id: genId(), ...item }];
      setContent(c => ({ ...c, [key]: newList }));
      saveSection(key, newList);
    },
    edit: (id, data) => {
      const newList = contentRef.current[key].map(i => i.id === id ? { ...i, ...data } : i);
      setContent(c => ({ ...c, [key]: newList }));
      saveSection(key, newList);
    },
    delete: (id) => {
      const newList = contentRef.current[key].filter(i => i.id !== id);
      setContent(c => ({ ...c, [key]: newList }));
      saveSection(key, newList);
    },
    reorder: (newList) => {
      const normalized = newList.map((item, i) => ({ ...item, order: i }));
      setContent(c => ({ ...c, [key]: normalized }));
      saveSection(key, normalized);
    },
  });

  const handlers = {
    updateBrand: (data) => {
      setContent(c => ({ ...c, brand: { ...c.brand, ...data } }));
      saveSection('brand', { ...contentRef.current.brand, ...data });
    },
    updateHero: (data) => {
      setContent(c => ({ ...c, hero: data }));
      saveSection('hero', data);
    },
    updateAbout: (data) => {
      const updated = { ...contentRef.current.about, ...data };
      setContent(c => ({ ...c, about: updated }));
      saveSection('about', updated);
    },
    updateAboutTestimonial: (data) => {
      const updated = { ...contentRef.current.about, testimonial: { ...contentRef.current.about.testimonial, ...data } };
      setContent(c => ({ ...c, about: updated }));
      saveSection('about', updated);
    },
    painPoints: {
      add:    (item) => { const nl = [...contentRef.current.about.painPoints, { id: genId(), ...item }]; const u = { ...contentRef.current.about, painPoints: nl }; setContent(c => ({ ...c, about: u })); saveSection('about', u); },
      edit:   (id, data) => { const nl = contentRef.current.about.painPoints.map(p => p.id === id ? { ...p, ...data } : p); const u = { ...contentRef.current.about, painPoints: nl }; setContent(c => ({ ...c, about: u })); saveSection('about', u); },
      delete: (id) => { const nl = contentRef.current.about.painPoints.filter(p => p.id !== id); const u = { ...contentRef.current.about, painPoints: nl }; setContent(c => ({ ...c, about: u })); saveSection('about', u); },
    },
    stats: {
      add:    (item) => { const nl = [...contentRef.current.about.stats, { id: genId(), ...item }]; const u = { ...contentRef.current.about, stats: nl }; setContent(c => ({ ...c, about: u })); saveSection('about', u); },
      edit:   (id, data) => { const nl = contentRef.current.about.stats.map(s => s.id === id ? { ...s, ...data } : s); const u = { ...contentRef.current.about, stats: nl }; setContent(c => ({ ...c, about: u })); saveSection('about', u); },
      delete: (id) => { const nl = contentRef.current.about.stats.filter(s => s.id !== id); const u = { ...contentRef.current.about, stats: nl }; setContent(c => ({ ...c, about: u })); saveSection('about', u); },
    },
    services: makeListHandlers('services'),
    reviews:  makeListHandlers('reviews'),
    process:  makeListHandlers('process'),
    works:    makeListHandlers('works'),
    faq:      makeListHandlers('faq'),
    partners: makeListHandlers('partners'),
    editPlan: (id, data) => {
      const newList = contentRef.current.pricing.map(p => p.id === id ? { ...p, ...data } : p);
      setContent(c => ({ ...c, pricing: newList }));
      saveSection('pricing', newList);
    },
  };

  // ── Auth gate ─────────────────────────────────────────────────────────────

  if (authLoading) {
    return (
      <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--bg-page)' }}>
        <div style={{ fontSize: 'var(--fs-body-sm)', color: 'var(--fg-secondary)' }}>Loading…</div>
      </div>
    );
  }

  if (!session) {
    return <Login />;
  }

  // ── Main admin ────────────────────────────────────────────────────────────

  const newCount = requests.filter(r => r.status === 'new').length;

  const renderPage = () => {
    if (loading) {
      return (
        <div style={{ padding: 'var(--space-16)', textAlign: 'center', color: 'var(--fg-secondary)' }}>
          Loading…
        </div>
      );
    }
    switch (page) {
      case 'dashboard': return <Dashboard requests={requests} />;
      case 'requests':  return <Requests  requests={requests} onStatusChange={handleStatusChange} />;
      case 'bookings':  return <Bookings  bookings={bookings} />;
      case 'blog':      return <Blog />;
      case 'signwall':  return <SignWall  items={signWall} onHide={handleHideSignWall} />;
      case 'content':   return <Content   content={content} handlers={handlers} lang={lang} setLang={setLang} />;
      case 'legal':     return <Legal     pages={legalPages} onSave={handleLegalSave} lang={lang} setLang={setLang} />;
      case 'users':     return <Users />;
      case 'settings':  return <Settings />;
      default:          return <Dashboard requests={requests} />;
    }
  };

  return (
    <Layout
      activePage={page}
      onNavigate={setPage}
      title={PAGE_TITLES[page]}
      newCount={newCount}
      role={CURRENT_ROLE}
      onSignOut={handleSignOut}
      userEmail={session.user?.email}
    >
      {renderPage()}
    </Layout>
  );
}

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