// Haikara Tracking — App-Shell: Auth-Gate, State-Store, Routing, Actions.
// Lädt Sendungen aus /api/tracking, hält den lokalen State und reicht
// { data, actions, route, setRoute } an die Screens (nav/dashboard/detail/add).
const { useState: useS, useEffect: useE, useCallback: useC, useRef: useRf } = React;
const { Icon: AppIcon } = window.HaikaraDesignSystem_df3594;

const STORE_KEY = 'haikara-tracking-route';

function LoginGate() {
  return (
    <div style={{ height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column', gap: 18, padding: 24, textAlign: 'center' }}>
      <div className="hk-breathe" style={{ width: 54, height: 54, borderRadius: 13, background: 'linear-gradient(135deg, var(--accent), #0d9488)', display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: '0 0 26px -6px var(--accent-glow)' }}>
        <AppIcon name="package" size={26} color="#04201d" />
      </div>
      <div>
        <h1 style={{ margin: '0 0 6px', fontSize: 26, fontWeight: 800, letterSpacing: '-0.01em', color: 'var(--text)' }}>Haikara Tracking</h1>
        <p style={{ margin: 0, fontSize: 13.5, color: 'var(--text-muted)' }}>Dein Sendungs-Cockpit. Melde dich an, um deine Pakete zu verfolgen.</p>
      </div>
      <button onClick={() => window.hkAuth && window.hkAuth.loginRedirect && window.hkAuth.loginRedirect()}
        style={{ padding: '10px 20px', borderRadius: 10, background: 'var(--accent)', color: '#04201d', border: 'none', fontWeight: 700, fontSize: 13.5, fontFamily: 'var(--font-sans)', cursor: 'pointer', boxShadow: '0 0 20px -6px var(--accent-glow)' }}>
        Anmelden
      </button>
    </div>
  );
}

function App() {
  const [route, setRouteRaw] = useS(() => {
    try { const s = JSON.parse(localStorage.getItem(STORE_KEY)); if (s && s.page) return s; } catch (e) {}
    return { page: 'dashboard', filter: 'all' };
  });
  const [dark, setDark] = useS(true);
  const [user, setUser] = useS(null);
  const [loading, setLoading] = useS(true);
  const [shipments, setShipments] = useS([]);
  const [toast, setToast] = useS(null);
  const toastTimer = useRf(null);

  const setRoute = useC((r) => setRouteRaw(r), []);

  useE(() => { document.documentElement.setAttribute('data-theme', dark ? 'dark' : 'light'); }, [dark]);
  useE(() => { try { localStorage.setItem(STORE_KEY, JSON.stringify(route)); } catch (e) {} }, [route]);

  const flash = useC((msg, kind) => {
    setToast({ msg, kind: kind || 'info' });
    clearTimeout(toastTimer.current);
    toastTimer.current = setTimeout(() => setToast(null), 2600);
  }, []);

  const reload = useC(async () => {
    try {
      const list = await window.trackingApi.loadShipments(route.page === 'archive' ? true : false);
      setShipments(list);
    } catch (e) { console.error('tracking load:', e); }
  }, [route.page]);

  // Auth + Initial-Load
  useE(() => {
    let alive = true;
    (async () => {
      const u = (window.hkAuth && window.hkAuth.getCurrentUser)
        ? await window.hkAuth.getCurrentUser().catch(() => null) : null;
      if (!alive) return;
      setUser(u || null);
      if (!u) { setLoading(false); return; }
      await reload();
      if (alive) setLoading(false);
    })();
    return () => { alive = false; };
  }, []);

  // Beim Wechsel aktive ⇄ Archiv neu laden.
  useE(() => { if (user) reload(); }, [route.page === 'archive']);

  // ── Actions ─────────────────────────────────────────────────────────────────
  const actions = {
    reload,
    flash,
    getDetail: (id) => window.trackingApi.getShipment(id),
    add: async (payload) => {
      const res = await window.trackingApi.addShipment(payload);
      if (res.shipment) { await reload(); flash('Sendung hinzugefügt.', 'success'); return res; }
      if (res.status === 409) flash('Diese Sendung verfolgst du bereits.', 'warn');
      else flash(res.error || 'Konnte nicht hinzufügen.', 'danger');
      return res;
    },
    refresh: async (id) => {
      const res = await window.trackingApi.refreshShipment(id);
      if (res.shipment) {
        if (res.shipment.provider === 'manual') flash('Manuelle Sendung — Status pflegst du selbst.', 'info');
        else flash(res.newCheckpoints ? `${res.newCheckpoints} neue Checkpoints.` : 'Keine Änderung.', 'success');
        await reload();
        return res.shipment;
      }
      flash(res.error || 'Aktualisierung fehlgeschlagen.', 'danger');
      return null;
    },
    addEvent: async (id, ev) => {
      const s = await window.trackingApi.addEvent(id, ev);
      if (s) { await reload(); flash('Checkpoint hinzugefügt.', 'success'); }
      else flash('Konnte Checkpoint nicht speichern.', 'danger');
      return s;
    },
    archive: async (id, archived) => {
      const s = await window.trackingApi.updateShipment(id, { archived: archived !== false });
      if (s) { await reload(); flash(archived !== false ? 'Archiviert.' : 'Wiederhergestellt.', 'success'); }
      return s;
    },
    setStatus: async (id, status) => {
      const s = await window.trackingApi.updateShipment(id, { status });
      if (s) await reload();
      return s;
    },
    remove: async (id) => {
      const ok = await window.trackingApi.removeShipment(id);
      if (ok) { await reload(); flash('Gelöscht.', 'success'); }
      else flash('Löschen fehlgeschlagen (fehlt dir die Berechtigung?).', 'danger');
      return ok;
    },
  };

  if (loading) {
    return <div style={{ height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--text-muted)' }}>// lädt…</div>;
  }
  if (!user) return <LoginGate />;

  // Activity synthetisieren: jüngster bekannter Stand je Sendung (das Backend hat
  // (noch) keinen app-weiten Event-Feed — v1 zeigt eine Zeile pro Sendung).
  const activity = shipments
    .map((s) => ({ id: 'act-' + s.id, pkg: s.id, carrier: s.carrier, label: window.trkStatusMeta(s.status).label, loc: s.loc, t: s.updated, status: s.status, title: s.title }))
    .sort((a, b) => new Date(b.t || 0) - new Date(a.t || 0));

  const data = { user, packages: shipments, activity };

  let screen;
  if (route.page === 'detail') screen = <window.TrackingDetail data={data} actions={actions} route={route} setRoute={setRoute} />;
  else if (route.page === 'add') screen = <window.TrackingAdd data={data} actions={actions} setRoute={setRoute} />;
  else if (route.page === 'activity') screen = <window.TrackingActivity data={data} setRoute={setRoute} />;
  else screen = <window.TrackingDashboard data={data} actions={actions} route={route} setRoute={setRoute} />;

  return (
    <div style={{ display: 'flex', height: '100%' }}>
      <window.TrackingSidebar route={route} setRoute={setRoute} data={data} dark={dark} setDark={setDark} />
      <main style={{ flex: 1, minWidth: 0, overflowY: 'auto', display: 'flex', flexDirection: 'column', position: 'relative' }}>
        {screen}
        {toast && (
          <div style={{
            position: 'fixed', bottom: 22, left: '50%', transform: 'translateX(-50%)', zIndex: 50,
            padding: '10px 16px', borderRadius: 10, fontSize: 12.5, fontWeight: 600, fontFamily: 'var(--font-sans)',
            background: 'var(--surface-2)', color: 'var(--text)', border: `1px solid ${toast.kind === 'danger' ? 'var(--danger)' : toast.kind === 'warn' ? 'var(--warn)' : toast.kind === 'success' ? 'var(--success)' : 'var(--border)'}`,
            boxShadow: '0 12px 32px rgba(0,0,0,.35)', backdropFilter: 'blur(6px)',
          }}>{toast.msg}</div>
        )}
      </main>
    </div>
  );
}
ReactDOM.createRoot(document.getElementById('root')).render(<App />);
