// ============================================================
// App entry — fetches live data from /api/data, then renders
// ============================================================

const { useState, useEffect, useCallback } = React;

// Minimal theme-tweak hook (replaces tweaks-panel.jsx dependency)
function useTweaks(defaults) {
  const [tweaks, setTweaksState] = useState(defaults);
  const setTweak = useCallback((key, value) => {
    setTweaksState(prev => ({ ...prev, [key]: value }));
  }, []);
  return [tweaks, setTweak];
}

function App() {
  const [data, setData]   = useState(null);
  const [error, setError] = useState(null);
  const [tweaks, setTweak] = useTweaks({ theme: "dark" });

  // Fetch all page data from server
  useEffect(() => {
    fetch('/api/data')
      .then(r => { if (!r.ok) throw new Error(r.statusText); return r.json(); })
      .then(d => {
        window.VIBE_POOL = d.VIBE_POOL;
        // Apply custom background if set, otherwise the CSS fallback (setup-bg.png) kicks in
        if (d.PROFILE?.bgImage) {
          document.documentElement.style.setProperty('--scene-bg-img', `url("${d.PROFILE.bgImage}")`);
        } else {
          document.documentElement.style.removeProperty('--scene-bg-img');
        }
        // Apply theme accent colors (mode-independent) from admin settings
        if (d.THEME) {
          const root = document.documentElement.style;
          if (d.THEME.cherry) root.setProperty('--cherry', d.THEME.cherry);
          if (d.THEME.lime)   root.setProperty('--lime', d.THEME.lime);
          if (d.THEME.orange) root.setProperty('--orange', d.THEME.orange);
          if (d.THEME.mode)   setTweak('theme', d.THEME.mode);
        }
        setData(d);
      })
      .catch(err => {
        console.error('Failed to load data:', err);
        setError(err.message);
      });
  }, []);

  useEffect(() => {
    document.documentElement.setAttribute("data-theme", tweaks.theme);
    // Custom background base colour applies to dark mode only; light keeps its own palette
    const bg = data?.THEME?.bgBase;
    if (bg) {
      if (tweaks.theme === 'dark') document.documentElement.style.setProperty('--bg-base', bg);
      else document.documentElement.style.removeProperty('--bg-base');
    }
  }, [tweaks.theme, data]);

  // Mouse-follow glow on link tiles
  useEffect(() => {
    const handler = (e) => {
      const tile = e.target.closest(".link-tile");
      if (!tile) return;
      const r = tile.getBoundingClientRect();
      tile.style.setProperty("--mx", `${e.clientX - r.left}px`);
      tile.style.setProperty("--my", `${e.clientY - r.top}px`);
    };
    document.addEventListener("mousemove", handler);
    return () => document.removeEventListener("mousemove", handler);
  }, []);

  const toggleTheme = () => setTweak("theme", tweaks.theme === "dark" ? "light" : "dark");

  const Scene = () => (
    <div className="scene" aria-hidden="true">
      <span className="blob b1"></span>
      <span className="blob b2"></span>
      <span className="blob b3"></span>
    </div>
  );

  if (error) {
    return (
      <>
        <Scene />
        <div style={{ display:'flex', alignItems:'center', justifyContent:'center', minHeight:'100vh', flexDirection:'column', gap:'1rem', color:'var(--text-mute)', fontFamily:'JetBrains Mono, monospace', fontSize:'0.85rem' }}>
          <span style={{ color:'var(--cherry)' }}>⚠</span>
          <span>Seite konnte nicht geladen werden</span>
          <button onClick={() => window.location.reload()} style={{ color:'var(--lime)', background:'none', border:'1px solid var(--border)', borderRadius:'8px', padding:'0.5rem 1rem', cursor:'pointer', fontFamily:'inherit' }}>
            neu laden
          </button>
        </div>
      </>
    );
  }

  if (!data) {
    return (
      <>
        <Scene />
        <div style={{ display:'flex', alignItems:'center', justifyContent:'center', minHeight:'100vh', color:'var(--text-mute)', fontFamily:'JetBrains Mono, monospace', fontSize:'0.85rem', letterSpacing:'0.05em' }}>
          loading...
        </div>
      </>
    );
  }

  const { PROFILE, STATS, LINKS, REELS, VIBE_POOL, CONFIG = {}, VIDEO, SECTIONS } = data;

  // Build an initial VIBE so VibeCheck has something before its first reroll
  const VIBE = {
    mood:        VIBE_POOL.mood[0],
    status:      VIBE_POOL.status[0],
    streamChance: 42,
    lastStream:   VIBE_POOL.lastStream[0],
    nextMaybe:    VIBE_POOL.next[0],
    coffees:      3,
  };

  // Map section keys to their components — order/visibility driven by admin settings
  const sectionFor = (key) => {
    switch (key) {
      case 'stats': return <StatsStrip stats={STATS} />;
      case 'vibe':  return <VibeCheck vibe={VIBE} />;
      case 'links': return <LinksGrid links={LINKS} />;
      case 'video': return <VideoSection video={VIDEO} />;
      case 'reels': return <ReelsSection reels={REELS} config={CONFIG} />;
      default:      return null;
    }
  };

  // Fall back to the classic order if the server sent nothing usable
  const order = (Array.isArray(SECTIONS) && SECTIONS.length)
    ? SECTIONS
    : [{ key: 'stats', on: true }, { key: 'vibe', on: true }, { key: 'links', on: true }, { key: 'video', on: true }, { key: 'reels', on: true }];

  return (
    <>
      <Scene />

      <button className="theme-toggle" onClick={toggleTheme} aria-label="Toggle theme">
        <Icon name={tweaks.theme === "dark" ? "sun" : "moon"} />
      </button>

      <main className="app">
        <div className="page">
          <span className="brandchip">
            <span className="dot"></span>
            <span data-edit-key="brandchip_text">{CONFIG.brandchip || 'Frau Kirsche · Bio'}</span>
          </span>

          <ProfileHeader profile={PROFILE} />
          <LiveCard profile={PROFILE} />

          {order.filter(s => s.on).map(s => (
            <React.Fragment key={s.key}>{sectionFor(s.key)}</React.Fragment>
          ))}

          <footer className="footer">
            {CONFIG.footer || <>made with <span className="heart">♥</span> · by Benetastic</>}
          </footer>
        </div>
      </main>
    </>
  );
}

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