// app.jsx — Main app shell, routing, state management

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "palette": 3,
  "font": 2
}/*EDITMODE-END*/;

// 4 curated accent palettes
const PALETTES = [
  { name: 'Korall (Standard)', primary: '#D97757', deep: '#B85A3C', soft: '#FAEDE4', ink: '#5C2E1B' },
  { name: 'Tiefblau',          primary: '#2A6FDB', deep: '#1F58B0', soft: '#E1ECF9', ink: '#0F2B5C' },
  { name: 'Waldgrün',          primary: '#3F8F5C', deep: '#2A6E45', soft: '#E0EFE5', ink: '#1E4730' },
  { name: 'Gold',              primary: '#C28428', deep: '#9A6618', soft: '#FAF1DD', ink: '#5C3F0E' },
];

// 4 curated typography bundles (body + display + tracking adj.)
const FONTS = [
  {
    name: 'Editorial',
    sans: "'Plus Jakarta Sans', -apple-system, system-ui, sans-serif",
    display: "'Instrument Serif', 'Plus Jakarta Sans', serif",
    displayWeight: 400, sansTrack: -0.01, displayTrack: -0.02,
    sample: { sans: 'Aa', display: 'Aa' },
  },
  {
    name: 'Geometrisch',
    sans: "'Space Grotesk', system-ui, sans-serif",
    display: "'Bricolage Grotesque', 'Space Grotesk', sans-serif",
    displayWeight: 500, sansTrack: -0.005, displayTrack: -0.03,
    sample: { sans: 'Aa', display: 'Aa' },
  },
  {
    name: 'Klassisch',
    sans: "'Manrope', system-ui, sans-serif",
    display: "'Newsreader', 'Manrope', serif",
    displayWeight: 500, sansTrack: -0.005, displayTrack: -0.015,
    sample: { sans: 'Aa', display: 'Aa' },
  },
  {
    name: 'Skandinavisch',
    sans: "'DM Sans', system-ui, sans-serif",
    display: "'Fraunces', 'DM Sans', serif",
    displayWeight: 400, sansTrack: -0.01, displayTrack: -0.02,
    sample: { sans: 'Aa', display: 'Aa' },
  },
];

// ─── Font bundle picker (custom — shows preview Aa) ─────────────────────
function FontBundlePicker({ value, onChange }) {
  return (
    <div style={{
      display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, padding: '6px 0',
    }}>
      {FONTS.map((f, i) => {
        const on = i === value;
        return (
          <button
            key={i} type="button"
            onClick={() => onChange(i)}
            style={{
              background: on ? '#1F1A14' : '#FAF7F2',
              color: on ? '#fff' : '#1F1A14',
              border: on ? '2px solid #D97757' : '1px solid #E0DACF',
              borderRadius: 12, padding: '12px 10px', cursor: 'pointer',
              display: 'flex', flexDirection: 'column', gap: 6, textAlign: 'left',
              transition: 'all .15s ease',
            }}
          >
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 4 }}>
              <span style={{
                fontFamily: f.display, fontWeight: f.displayWeight, fontSize: 32,
                lineHeight: 0.9, letterSpacing: f.displayTrack + 'em',
              }}>Aa</span>
              <span style={{
                fontFamily: f.sans, fontWeight: 600, fontSize: 14,
                opacity: 0.65, letterSpacing: f.sansTrack + 'em',
              }}>Aa</span>
            </div>
            <div style={{
              fontFamily: f.sans, fontSize: 11, fontWeight: 600,
              letterSpacing: -0.005, marginTop: 2,
            }}>{f.name}</div>
          </button>
        );
      })}
    </div>
  );
}


function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const palette = PALETTES[t.palette] || PALETTES[0];
  const font = FONTS[t.font] || FONTS[0];

  // Apply palette + font tokens to CSS vars
  React.useEffect(() => {
    const r = document.documentElement;
    r.style.setProperty('--primary', palette.primary);
    r.style.setProperty('--primary-deep', palette.deep);
    r.style.setProperty('--primary-soft', palette.soft);
    r.style.setProperty('--primary-ink', palette.ink);
    r.style.setProperty('--font-sans', font.sans);
    r.style.setProperty('--font-display', font.display);
    r.style.setProperty('--font-display-weight', font.displayWeight);
  }, [t.palette, t.font]);

  // App state
  const [authed, setAuthed] = React.useState(true); // start logged in for instant demo
  const [tab, setTab] = React.useState('immobilien'); // bottom nav root
  // Stack: array of { name, params } per tab — but simpler: single stack
  const [stack, setStack] = React.useState([{ name: 'dashboard', params: null }]);

  const [searches, setSearches] = React.useState(window.SEARCHES);
  const [listings] = React.useState(window.LISTINGS);
  const [favs, setFavs] = React.useState(new Set(['l3', 'l8']));
  const [archived, setArchived] = React.useState(new Set());
  const [notifications, setNotifications] = React.useState(window.NOTIFICATIONS);
  const notifBadge = notifications.filter(n => !n.read).length;

  // Navigation API
  const navigate = (name, params = null, replace = false) => {
    setStack(s => replace ? [...s.slice(0, -1), { name, params }] : [...s, { name, params }]);
  };
  const back = () => {
    setStack(s => s.length > 1 ? s.slice(0, -1) : s);
  };
  const reset = (name, params = null) => {
    setStack([{ name, params }]);
  };

  const toggleFav = (id, forceOn) => {
    setFavs(s => {
      const ns = new Set(s);
      if (forceOn) ns.add(id);
      else if (ns.has(id)) ns.delete(id);
      else ns.add(id);
      return ns;
    });
  };
  const archiveListing = (id) => setArchived(s => new Set([...s, id]));
  const addSearch = (s) => setSearches(arr => [s, ...arr]);
  const deleteSearch = (id) => setSearches(arr => arr.filter(s => s.id !== id));

  // Switching tabs resets the stack to the root of that tab
  const setActiveTab = (newTab) => {
    setTab(newTab);
    const roots = {
      immobilien: 'dashboard',
      mieten: 'mietenDashboard',
      portfolio: 'portfolio',
      notifications: 'notifications',
      profile: 'profile',
    };
    reset(roots[newTab]);
  };

  const ctx = {
    listings, searches, favs, archived, notifications, notifBadge,
    navigate, back, reset,
    toggleFav, archiveListing,
    addSearch, deleteSearch, setNotifications,
    signOut: () => { setAuthed(false); reset('dashboard'); },
  };

  // Resolve current screen
  const current = stack[stack.length - 1];
  let screen = null;
  switch (current.name) {
    case 'dashboard':        screen = <DashboardScreen ctx={ctx} />; break;
    case 'searchBuilder':    screen = <SearchBuilderScreen ctx={ctx} type="kauf" />; break;
    case 'searchBuilderMiete': screen = <SearchBuilderScreen ctx={ctx} type="miete" />; break;
    case 'results':          screen = <ResultsScreen ctx={ctx} searchId={current.params?.searchId} />; break;
    case 'mietenResults':    screen = <ResultsScreen ctx={ctx} searchId={current.params?.searchId} />; break;
    case 'listing':          screen = <ListingDetailScreen ctx={ctx} id={current.params?.id} />; break;
    case 'aiEval':           screen = <AIEvalScreen ctx={ctx} id={current.params?.id} />; break;
    case 'mietenDashboard':  screen = <MietenDashboardScreen ctx={ctx} />; break;
    case 'swipe':            screen = <SwipeScreen ctx={ctx} />; break;
    case 'portfolio':        screen = <PortfolioScreen ctx={ctx} />; break;
    case 'notifications':    screen = <NotificationsScreen ctx={ctx} />; break;
    case 'profile':          screen = <ProfileScreen ctx={ctx} />; break;
    case 'admin':            screen = <AdminScreen ctx={ctx} />; break;
    default:                 screen = <DashboardScreen ctx={ctx} />;
  }

  // Hide bottom nav for fullscreen flows
  const hideNav = ['searchBuilder', 'searchBuilderMiete', 'listing', 'aiEval', 'swipe', 'admin'].includes(current.name);
  // Status bar in dark mode on dark screens
  const statusDark = !authed || current.name === 'swipe';

  if (!authed) {
    return (
      <>
        <PhoneFrame statusDark={true}>
          <LandingScreen onEnter={() => { setAuthed(true); reset('dashboard'); }} />
        </PhoneFrame>
        <TweaksPanel title="Tweaks" noDeckControls>
          <TweakSection label="Akzentfarbe">
            <TweakColor
              label="Palette"
              value={PALETTES[t.palette].primary}
              options={PALETTES.map(p => [p.primary, p.deep, p.soft])}
              onChange={(v) => {
                const idx = PALETTES.findIndex(p => p.primary === (Array.isArray(v) ? v[0] : v));
                if (idx >= 0) setTweak('palette', idx);
              }}
            />
          </TweakSection>
          <TweakSection label="Schriftart">
            <FontBundlePicker value={t.font || 0} onChange={(i) => setTweak('font', i)} />
          </TweakSection>
        </TweaksPanel>
      </>
    );
  }

  return (
    <>
      <PhoneFrame statusDark={statusDark}>
        <div key={current.name + JSON.stringify(current.params)} className="fade-in" style={{ height: '100%' }}>
          {screen}
        </div>
        {!hideNav && (
          <BottomNav active={tab} onTab={setActiveTab} notifBadge={notifBadge} />
        )}
      </PhoneFrame>
      <TweaksPanel title="Tweaks" noDeckControls>
        <TweakSection label="Akzentfarbe">
          <TweakColor
            label="Palette"
            value={PALETTES[t.palette].primary}
            options={PALETTES.map(p => [p.primary, p.deep, p.soft])}
            onChange={(v) => {
              const idx = PALETTES.findIndex(p => p.primary === (Array.isArray(v) ? v[0] : v));
              if (idx >= 0) setTweak('palette', idx);
            }}
          />
        </TweakSection>
        <TweakSection label="Schriftart">
          <FontBundlePicker value={t.font || 0} onChange={(i) => setTweak('font', i)} />
        </TweakSection>
        <TweakSection label="Demo-Navigation">
          <TweakSelect
            label="Zu Screen springen"
            value={current.name}
            options={[
              { value: 'dashboard',          label: 'Immobilien Dashboard' },
              { value: 'searchBuilder',      label: 'Suche erstellen (Kauf)' },
              { value: 'results',            label: 'Suchergebnisse' },
              { value: 'listing',            label: 'Inserat-Detail' },
              { value: 'aiEval',             label: 'KI-Bewertung' },
              { value: 'mietenDashboard',    label: 'Mieten Dashboard' },
              { value: 'swipe',              label: 'Swipe entdecken' },
              { value: 'portfolio',          label: 'Merkliste / Portfolio' },
              { value: 'notifications',      label: 'Mitteilungen' },
              { value: 'profile',            label: 'Profil' },
              { value: 'admin',              label: 'Admin Job-Monitor' },
              { value: 'landing',            label: 'Landing / Login' },
            ]}
            onChange={(v) => {
              if (v === 'landing') { setAuthed(false); return; }
              const tabMap = {
                dashboard: 'immobilien', searchBuilder: 'immobilien', results: 'immobilien', listing: 'immobilien', aiEval: 'immobilien',
                mietenDashboard: 'mieten', mietenResults: 'mieten',
                portfolio: 'portfolio', notifications: 'notifications', profile: 'profile',
                swipe: 'immobilien', admin: 'profile',
              };
              const params =
                v === 'results' ? { searchId: 's1' } :
                v === 'mietenResults' ? { searchId: 's4' } :
                v === 'listing' ? { id: 'l3' } :
                v === 'aiEval' ? { id: 'l3' } :
                null;
              setTab(tabMap[v] || 'immobilien');
              reset(v, params);
            }}
          />
        </TweakSection>
      </TweaksPanel>
    </>
  );
}

// ─── Phone frame wrapper that auto-fits viewport ─────────────────────────
function PhoneFrame({ children, statusDark = false }) {
  const ref = React.useRef(null);
  const [scale, setScale] = React.useState(1);
  const W = 402, H = 874;

  React.useEffect(() => {
    const fit = () => {
      const vw = window.innerWidth;
      const vh = window.innerHeight;
      const pad = 40;
      const s = Math.min((vw - pad) / W, (vh - pad) / H, 1);
      setScale(s);
    };
    fit();
    window.addEventListener('resize', fit);
    return () => window.removeEventListener('resize', fit);
  }, []);

  return (
    <div style={{
      position: 'fixed', inset: 0,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      background: 'radial-gradient(120% 100% at 50% 0%, #423931 0%, #1F1A14 100%)',
    }}>
      <div ref={ref} style={{
        width: W, height: H, transform: `scale(${scale})`, transformOrigin: 'center center',
        position: 'relative',
      }}>
        {/* iPhone frame: outer shell */}
        <div style={{
          width: W, height: H, borderRadius: 48, overflow: 'hidden',
          position: 'relative', background: 'var(--bg)',
          boxShadow: '0 40px 80px rgba(0,0,0,.5), 0 0 0 8px #1A1612, 0 0 0 9px #3A322A',
          fontFamily: 'var(--font-sans)',
          WebkitFontSmoothing: 'antialiased',
        }}>
          {/* dynamic island */}
          <div style={{
            position: 'absolute', top: 11, left: '50%', transform: 'translateX(-50%)',
            width: 126, height: 37, borderRadius: 24, background: '#000', zIndex: 200,
            pointerEvents: 'none',
          }} />
          {/* status bar */}
          <div style={{ position: 'absolute', top: 0, left: 0, right: 0, zIndex: 195, pointerEvents: 'none' }}>
            <IOSStatusBar dark={statusDark} time="9:41" />
          </div>
          {/* content */}
          <div style={{ height: '100%', width: '100%', position: 'relative', overflow: 'hidden' }}>
            {children}
          </div>
          {/* home indicator */}
          <div style={{
            position: 'absolute', bottom: 8, left: '50%', transform: 'translateX(-50%)',
            width: 139, height: 5, borderRadius: 999,
            background: statusDark ? 'rgba(255,255,255,.5)' : 'rgba(0,0,0,.25)', zIndex: 250, pointerEvents: 'none',
          }} />
        </div>
      </div>
    </div>
  );
}

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