// Main Huul app — state management, routing, Tweaks.

const { useState: useSa, useEffect: useEa, useMemo: useMa } = React;

const STORAGE_KEY = 'huul.state.v2';

function HuulApp({ tweaks, onTweaksChange }) {
  // ─── Persisted state ──────────────────────────────────────
  const [state, setState] = useSa(() => {
    try {
      const saved = localStorage.getItem(STORAGE_KEY);
      if (saved) return JSON.parse(saved);
    } catch (e) {}
    return {
      onboarded: false,
      profile: null,
      products: [],
    };
  });

  useEa(() => {
    try { localStorage.setItem(STORAGE_KEY, JSON.stringify(state)); } catch (e) {}
  }, [state]);

  // ─── Navigation ──────────────────────────────────────────
  // views: 'onboard' | 'profile' | 'shop' | 'product' | 'dashboard' | 'editor' | 'bio' | 'editProfile' | 'editSocials' | 'editLinks'
  const [view, setView] = useSa(state.onboarded ? 'profile' : 'onboard');
  const [activeProduct, setActiveProduct] = useSa(null);
  const [editingProduct, setEditingProduct] = useSa(null);
  const [whatsAppFor, setWhatsAppFor] = useSa(null);
  const [toast, showToast] = useToast();

  // Expose navigation bridges to the host chrome (left-panel navigator)
  useEa(() => {
    window.__huulGoto = (id) => {
      if (id === 'product') {
        const firstLive = state.products.find(p => p.published) || state.products[0];
        if (firstLive) setActiveProduct(firstLive);
      }
      if (id === 'editor') setEditingProduct({});
      setView(id);
    };
    window.__huulSetView = setView;
    window.__huulCurrentView = view;
  }, [view, state.products]);

  // ─── Reset ──────────────────────────────────────────────
  const reset = () => {
    localStorage.removeItem(STORAGE_KEY);
    setState({ onboarded: false, profile: null, products: [] });
    setView('onboard');
  };

  // ─── Actions ─────────────────────────────────────────────
  const finishOnboarding = (profileData) => {
    const profile = {
      ...profileData,
      socials: [],
      links: [],
    };
    setState({ onboarded: true, profile, products: [] });
    setView('profile');
  };

  const saveProduct = (p) => {
    setState(s => {
      const existing = s.products.find(x => x.id === p.id);
      const products = existing
        ? s.products.map(x => x.id === p.id ? p : x)
        : [p, ...s.products];
      return { ...s, products };
    });
    setView('dashboard');
    setEditingProduct(null);
    showToast('Saved');
  };

  const deleteProduct = (id) => {
    setState(s => ({ ...s, products: s.products.filter(x => x.id !== id) }));
    setView('dashboard');
    setEditingProduct(null);
    showToast('Deleted');
  };

  const togglePublished = (id) => {
    setState(s => ({
      ...s,
      products: s.products.map(x => x.id === id ? { ...x, published: !x.published } : x),
    }));
  };

  const updateProfile = (updatedProfile) => {
    setState(s => ({ ...s, profile: updatedProfile }));
  };

  const saveProfile = (updatedProfile) => {
    setState(s => ({ ...s, profile: updatedProfile }));
    setView('dashboard');
    showToast('Profile saved');
  };

  const saveSocials = (updatedProfile) => {
    setState(s => ({ ...s, profile: updatedProfile }));
    setView('dashboard');
    showToast('Socials saved');
  };

  const saveLinks = (updatedProfile) => {
    setState(s => ({ ...s, profile: updatedProfile }));
    setView('dashboard');
    showToast('Links saved');
  };

  const openWhatsAppFor = (product) => setWhatsAppFor(product);

  const sendWhatsApp = (message) => {
    // In a real app this would build a wa.me URL. We just toast.
    const number = state.profile.whatsapp.replace(/\D/g, '');
    const url = `https://wa.me/${number}?text=${encodeURIComponent(message)}`;
    showToast('Opening WhatsApp…');
    setWhatsAppFor(null);
    // simulate external navigation
    console.log('[Huul] Would open:', url);
  };

  // ─── Render by view ──────────────────────────────────────
  const profile = state.profile;
  const products = state.products;

  const showTabBar = view !== 'onboard';

  return (
    <HuulDevice bg={HUUL_TOKENS.color.bg}>
      <div style={{ position:'absolute', inset:0, overflow:'hidden' }}>
        {view === 'onboard' && <OnboardingFlow onComplete={finishOnboarding}/>}

        {view === 'profile' && profile && (
          <PublicProfile
            profile={profile} products={products}
            layout={tweaks.profileLayout}
            cardLayout={tweaks.cardLayout}
            onOpenShop={() => setView('shop')}
            onOpenProduct={(p) => { setActiveProduct(p); setView('product'); }}
            onShare={() => showToast('Link copied: huul.so/' + profile.username)}
            showEditHandles={tweaks.showEditHandles}
            onEditClick={(section) => {
              if (section === 'socials') setView('editSocials');
              else if (section === 'links') setView('editLinks');
              else setView('dashboard');
            }}
          />
        )}

        {view === 'shop' && profile && (
          <ShopScreen
            profile={profile} products={products}
            cardLayout={tweaks.cardLayout}
            onChangeCardLayout={(v) => onTweaksChange({ cardLayout: v })}
            onBack={() => setView('profile')}
            onOpenProduct={(p) => { setActiveProduct(p); setView('product'); }}
            onContactWhatsApp={openWhatsAppFor}
          />
        )}

        {view === 'product' && activeProduct && profile && (
          <ProductDetail
            product={activeProduct} profile={profile}
            onBack={() => setView(activeProduct._from === 'shop' ? 'shop' : 'profile')}
            onContactWhatsApp={openWhatsAppFor}
          />
        )}

        {view === 'dashboard' && profile && (
          <Dashboard
            profile={profile} products={products}
            onBack={() => setView('profile')}
            onOpenPublic={() => setView('profile')}
            onOpenShop={() => setView('shop')}
            onAddProduct={() => { setEditingProduct({}); setView('editor'); }}
            onEditProduct={(p) => { setEditingProduct(p); setView('editor'); }}
            onEditProfile={() => setView('editProfile')}
            onEditSocials={() => setView('editSocials')}
            onEditLinks={() => setView('editLinks')}
            onTogglePublished={togglePublished}
          />
        )}

        {view === 'editor' && (
          <ProductEditor
            initial={editingProduct}
            onSave={saveProduct}
            onDelete={deleteProduct}
            onClose={() => { setEditingProduct(null); setView('dashboard'); }}
          />
        )}

        {view === 'bio' && profile && (
          <BioScreen
            profile={profile}
            onUpdateProfile={updateProfile}
            onEditProfile={() => setView('editProfile')}
            onBack={() => setView('dashboard')}
          />
        )}

        {view === 'editProfile' && profile && (
          <ProfileEditorScreen
            profile={profile}
            onSave={saveProfile}
            onClose={() => setView('dashboard')}
          />
        )}

        {view === 'editSocials' && profile && (
          <SocialsEditorScreen
            profile={profile}
            onSave={saveSocials}
            onClose={() => setView('dashboard')}
          />
        )}

        {view === 'editLinks' && profile && (
          <LinksEditorScreen
            profile={profile}
            onSave={saveLinks}
            onClose={() => setView('dashboard')}
          />
        )}

        {view === 'analytics' && (
          <AnalyticsScreen />
        )}

        {view === 'settings' && (
          <SettingsScreen tweaks={tweaks} onTweaksChange={onTweaksChange} />
        )}

        <WhatsAppSheet
          open={!!whatsAppFor}
          product={whatsAppFor}
          profile={profile}
          onClose={() => setWhatsAppFor(null)}
          onSend={sendWhatsApp}
        />

        <Toast message={toast.message} visible={toast.visible}/>

        {showTabBar && (
          <TabBar
            tabStyle="B"
            active={
              view === 'profile' ? 'profile' :
              view === 'shop' || view === 'product' ? 'profile' :
              view === 'bio' ? 'bio' :
              view === 'analytics' ? 'analytics' :
              view === 'settings' ? 'settings' :
              'dashboard'
            }
            onTab={(t) => {
              if (t === 'profile')   setView('profile');
              if (t === 'bio')       setView('bio');
              if (t === 'dashboard') setView('dashboard');
              if (t === 'analytics') setView('analytics');
              if (t === 'settings')  setView('settings');
            }}
          />
        )}
      </div>
    </HuulDevice>
  );
}

window.HuulApp = HuulApp;
window.HuulReset = () => { localStorage.removeItem(STORAGE_KEY); location.reload(); };
