// Tempo — App shell (responsive, no design canvas wrapper)

function useIsMobile() {
  const [m, setM] = React.useState(() => typeof window !== 'undefined' && window.innerWidth < 900);
  React.useEffect(() => {
    const fit = () => setM(window.innerWidth < 900);
    window.addEventListener('resize', fit);
    return () => window.removeEventListener('resize', fit);
  }, []);
  return m;
}

function useAuthSession() {
  const [session, setSession] = React.useState(null);
  const [checked, setChecked] = React.useState(false);
  // Lien de récupération de mot de passe : Supabase connecte l'utilisateur avec
  // une session de récupération et émet PASSWORD_RECOVERY — on affiche alors
  // l'écran « nouveau mot de passe » avant d'entrer dans l'app.
  const [recovery, setRecovery] = React.useState(false);
  React.useEffect(() => {
    if (!window.sb) { setChecked(true); return; }
    let live = true;
    window.sb.auth.getSession().then(({ data }) => {
      if (!live) return;
      setSession(data?.session || null);
      setChecked(true);
    });
    const { data: sub } = window.sb.auth.onAuthStateChange((evt, sess) => {
      if (evt === 'PASSWORD_RECOVERY') setRecovery(true);
      setSession(sess || null);
    });
    return () => { live = false; try { sub.subscription.unsubscribe(); } catch (e) {} };
  }, []);
  const clearRecovery = React.useCallback(() => setRecovery(false), []);
  return { session, checked, recovery, clearRecovery };
}

// Catches render-time errors anywhere in the tree so one broken screen shows a
// graceful fallback instead of white-screening the whole app.
class ErrorBoundary extends React.Component {
  constructor(props) { super(props); this.state = { err: null }; }
  static getDerivedStateFromError(err) { return { err }; }
  componentDidCatch(err, info) { console.error('[Tempo] UI error:', err, info); }
  render() {
    if (this.state.err) {
      return (
        <div style={{ minHeight: '100vh', display: 'grid', placeItems: 'center', padding: 24, background: 'var(--bg-app)', color: 'var(--fg)' }}>
          <div style={{ maxWidth: 420, textAlign: 'center' }}>
            <div style={{ fontSize: 18, fontWeight: 700, marginBottom: 8 }}>Une erreur est survenue</div>
            <p style={{ fontSize: 13, color: 'var(--fg-3)', lineHeight: 1.5, marginBottom: 18 }}>
              Cette section a rencontré un problème. Tes données sont en sécurité. Recharge la page pour continuer.
            </p>
            <button onClick={() => window.location.reload()} className="btn btn-blue tap">Recharger Tempo</button>
          </div>
        </div>
      );
    }
    return this.props.children;
  }
}

function App() {
  const isMobile = useIsMobile();
  const [route, setRoute] = React.useState('home');
  const { session, checked, recovery, clearRecovery } = useAuthSession();
  const loggedIn = !!session;
  const [journalingOpen, setJournalingOpen] = React.useState(true);
  const [statsInitialView, setStatsInitialView] = React.useState('trading'); // 'trading' | 'habits' — sous-onglet d'ouverture de Statistiques
  const [modalDay, setModalDay] = React.useState(null); // ISO date string
  const [importOpen, setImportOpen] = React.useState(false);
  const [importForDay, setImportForDay] = React.useState(null); // ISO date string seeded into the trade date field
  const [tradeDetail, setTradeDetail] = React.useState(null); // trade row object
  const state = useAppState();
  const openTrade = (t) => setTradeDetail(t);
  const closeTrade = () => setTradeDetail(null);

  const handleLogout = async () => {
    try { await window.sb.auth.signOut(); } catch (e) {}
    // session listener will flip loggedIn → false
  };

  const openJournal = (d) => {
    // Accept: number (day-of-month) → build ISO with current month;
    // string ISO; {day} object; {date: 'XX mai'} fallback.
    if (typeof d === 'number') {
      setModalDay(buildISOFromDay(d));
      return;
    }
    if (d && typeof d === 'string') {
      setModalDay(d.slice(0, 10));
      return;
    }
    if (d && typeof d.day === 'number') {
      setModalDay(buildISOFromDay(d.day));
      return;
    }
    if (d && d.date && typeof d.date === 'string') {
      const m = d.date.match(/\d+/);
      if (m) { setModalDay(buildISOFromDay(parseInt(m[0], 10))); return; }
    }
    setModalDay(state.today);
  };

  const nav = (id) => {
    setRoute(id);
    const journalingRoutes = ['dashboard', 'trades', 'daily', 'stats', 'weekly', 'strategy', 'data'];
    if (journalingRoutes.includes(id)) setJournalingOpen(true);
  };

  // Navigate to the Statistiques section, pre-opening a sub-view ('trading'|'habits').
  // Used by clickable KPI cards on Home/Dashboard.
  const navStats = (view) => {
    setStatsInitialView(view === 'habits' ? 'habits' : 'trading');
    nav('stats');
  };

  // Accept an optional ISO day string (e.g. "2026-05-28"). When provided, the trade
  // form's date input is pre-filled with that day at the current local time.
  const openImport = (forDay) => {
    // Coerce: accept plain string ISO or null/undefined; ignore other types (e.g. event objects).
    const iso = (typeof forDay === 'string' && forDay) ? forDay.slice(0, 10) : null;
    setImportForDay(iso);
    setImportOpen(true);
  };
  const closeImport = (didImport) => {
    setImportOpen(false);
    setImportForDay(null);
    if (didImport) state.refreshTrades();
  };

  const renderRoute = () => {
    // Wrap each route so a single broken screen keeps the app shell (sidebar/nav) alive.
    // key={route} resets the boundary when the user navigates away.
    return <ErrorBoundary key={route}>{renderRouteInner()}</ErrorBoundary>;
  };

  const renderRouteInner = () => {
    switch (route) {
      case 'home':        return <Home nav={nav} navStats={navStats} openJournal={openJournal} openImport={openImport} openTrade={openTrade} state={state}/>;
      case 'routines':    return <RoutinesPage state={state}/>;
      case 'dashboard':   return <Gate feature="journal"><Dashboard nav={nav} navStats={navStats} openImport={openImport} openJournal={openJournal} openTrade={openTrade} state={state}/></Gate>;
      case 'trades':      return <Gate feature="journal"><TradesPage nav={nav} openJournal={openJournal} openImport={openImport} openTrade={openTrade} state={state}/></Gate>;
      case 'daily':       return <Gate feature="journal"><Daily nav={nav} openJournal={openJournal} openImport={openImport} state={state}/></Gate>;
      case 'weekly':      return <Gate feature="journal"><WeeklyPage state={state} openJournal={(week) => openJournal(week && week.key ? week.key : week)}/></Gate>;
      case 'strategy':    return <Gate feature="journal"><StrategyPage state={state}/></Gate>;
      case 'backtest':    return <Gate feature="backtest"><BacktestPage state={state}/></Gate>;
      case 'fondamental': return <Gate feature="fondamental"><FondamentalPage state={state}/></Gate>;
      case 'stats':       return <Gate feature="journal"><StatsPage state={state} initialView={statsInitialView}/></Gate>;
      case 'data':        return <Gate feature="journal"><Placeholder title="Gestion des données" sub="Import CSV, sync brokers, export, et nettoyage de ton historique." icon={Ico.data}/></Gate>;
      case 'econ':        return <EconomicCalendar nav={nav}/>;
      case 'settings':    return <SettingsPage state={state} onLogout={handleLogout} openImport={openImport}/>;
      default:            return <Home nav={nav} navStats={navStats} openJournal={openJournal} openImport={openImport} openTrade={openTrade} state={state}/>;
    }
  };

  // While we resolve the session, show nothing (boot loader takes care of UI)
  if (!checked) return null;

  // Lien de récupération de mot de passe : forcer la définition du nouveau
  // mot de passe AVANT d'entrer dans l'app (la session de récupération connecte
  // déjà l'utilisateur, sans cet écran il ne pourrait jamais le changer).
  if (recovery && typeof window.UpdatePassword === 'function') {
    return <window.UpdatePassword onDone={clearRecovery}/>;
  }

  if (!loggedIn) {
    return <Login onLogin={() => { /* session listener will flip state */ }}/>;
  }

  if (isMobile) {
    return (
      <React.Fragment>
        <MobileScreen active={route} onChange={nav} showNav={true}>
          <MobileContent route={route} nav={nav} navStats={navStats} statsInitialView={statsInitialView} openJournal={openJournal} openImport={openImport} openTrade={openTrade} state={state} onLogout={handleLogout}/>
        </MobileScreen>
        <JournalModal open={modalDay != null} dayISO={modalDay} onClose={() => setModalDay(null)} state={state} openImport={openImport} openTrade={openTrade}/>
        <ImportModal open={importOpen} onClose={closeImport} state={state} defaultDate={importForDay}/>
        <TradeDetailModal open={tradeDetail != null} trade={tradeDetail} onClose={closeTrade} state={state}/>
      </React.Fragment>
    );
  }

  return (
    <React.Fragment>
      <DesktopScreen active={route} onChange={nav} journalingOpen={journalingOpen} setJournalingOpen={setJournalingOpen} user={state.user} displayName={state.displayName}>
        {renderRoute()}
      </DesktopScreen>
      <JournalModal open={modalDay != null} dayISO={modalDay} onClose={() => setModalDay(null)} state={state} openImport={openImport} openTrade={openTrade}/>
      <ImportModal open={importOpen} onClose={closeImport} state={state} defaultDate={importForDay}/>
      <TradeDetailModal open={tradeDetail != null} trade={tradeDetail} onClose={closeTrade} state={state}/>
    </React.Fragment>
  );
}

// Build an ISO date string for "day d of the current viewed month" — defaults to current month/year.
function buildISOFromDay(d) {
  const now = new Date();
  const y = now.getFullYear();
  const m = String(now.getMonth() + 1).padStart(2, '0');
  const dd = String(d).padStart(2, '0');
  return `${y}-${m}-${dd}`;
}

function MobileContent(props) {
  // Wrap each mobile screen so a broken route keeps the bottom nav alive.
  return <ErrorBoundary key={props.route}>{MobileContentInner(props)}</ErrorBoundary>;
}

function MobileContentInner({ route, nav, navStats, statsInitialView, openJournal, openImport, openTrade, state, onLogout }) {
  switch (route) {
    case 'home':      return <HomeMobile nav={nav} navStats={navStats} openJournal={openJournal} openImport={openImport} openTrade={openTrade} state={state}/>;
    case 'dashboard': return <Gate feature="journal"><DashboardMobile state={state}/></Gate>;
    case 'trades':    return <Gate feature="journal"><TradesMobile openJournal={openJournal} openImport={openImport} openTrade={openTrade} state={state}/></Gate>;
    case 'daily':     return <Gate feature="journal"><DailyMobile openJournal={openJournal} state={state}/></Gate>;
    case 'weekly':    return <Gate feature="journal"><WeeklyMobile state={state} openJournal={(week) => openJournal(week && week.key ? week.key : week)}/></Gate>;
    case 'strategy':  return <Gate feature="journal"><StrategyMobile state={state}/></Gate>;
    case 'backtest':  return <Gate feature="backtest"><BacktestMobile state={state}/></Gate>;
    case 'fondamental': return <Gate feature="fondamental"><FondamentalMobile state={state}/></Gate>;
    case 'stats':     return <Gate feature="journal"><StatsMobile state={state} initialView={statsInitialView}/></Gate>;
    case 'routines':  return <RoutinesPage state={state}/>;
    case 'econ':      return <EconomicCalendar nav={nav}/>;
    case 'settings':  return <SettingsMobile state={state} onLogout={onLogout} openImport={openImport} nav={nav}/>;
    default:          return <HomeMobile nav={nav} navStats={navStats} openJournal={openJournal} openImport={openImport} openTrade={openTrade} state={state}/>;
  }
}

function HomeMobile({ nav, navStats, openJournal, openImport, openTrade, state }) {
  const t = useLiveTime();
  const goStatsTrading = navStats ? () => navStats('trading') : (nav ? () => nav('stats') : undefined);
  const { habits, toggleHabit, agenda, toggleAgenda, trades, stats, tradesLoading } = state;
  // Briefing marché live (titre adaptatif à l'heure + refresh auto gérés par le hook).
  const news = typeof useNewsBriefing === 'function' ? useNewsBriefing() : [];
  const newsTitle = typeof briefingTitle === 'function' ? briefingTitle(t.getHours()) : 'Briefing du marché';
  const ny  = tzTime(t, 'America/New_York');
  const ldn = tzTime(t, 'Europe/London');
  const par = tzTime(t, 'Europe/Paris');
  const parisHM = parisHourMinute(t);
  const sessions = sessionStatus(parisHM.h, parisHM.m, parisHM.d);
  const marketOpenCME = useMarketOpen();
  const dateLabel = buildDateLabel(new Date());
  // Greeting name: real display name (profile) with email/Trader fallbacks (see state.displayName).
  const greeting = state.displayName || '';
  const net = stats.netPnl || 0;
  const recent = trades.slice(0, 4);

  const heroPill = !marketOpenCME
    ? { text: 'Marchés fermés', open: false }
    : sessions.newyork
      ? { text: 'Session NY ouverte', open: true }
      : sessions.london
        ? { text: 'Session Londres ouverte', open: true }
        : { text: 'CME ouvert', open: true };

  return (
    <div style={{ padding: '8px 0 20px' }}>
      <div style={{ padding: '14px 20px 16px' }}>
        <div style={{ fontSize: 11.5, color: 'var(--fg-3)', fontWeight: 500, letterSpacing: '.02em', textTransform: 'uppercase', marginBottom: 8 }}>{dateLabel}</div>
        <h1 style={{ fontSize: 28, fontWeight: 700, letterSpacing: '-.025em', margin: 0, lineHeight: 1.1 }}>Bonjour {greeting}</h1>
      </div>

      <div style={{ padding: '0 20px 14px' }}>
        <div style={{ background: 'linear-gradient(135deg, #0f172a 0%, #0c4a6e 100%)', borderRadius: 16, padding: '20px 22px', color: '#fff', position: 'relative', overflow: 'hidden' }}>
          {heroPill.open ? (
            <span className="pill" style={{ background: 'rgba(34,197,94,0.20)', color: '#86efac', border: '1px solid rgba(34,197,94,0.35)' }}>
              <span style={{ width: 5, height: 5, borderRadius: '50%', background: '#22c55e', animation: 'pulse-dot 2s var(--ease) infinite' }}></span>
              {heroPill.text}
            </span>
          ) : (
            <span className="pill" style={{ background: 'rgba(255,255,255,0.10)', color: 'rgba(255,255,255,0.72)', border: '1px solid rgba(255,255,255,0.18)' }}>
              <span style={{ width: 5, height: 5, borderRadius: '50%', background: 'rgba(255,255,255,0.4)' }}></span>
              {heroPill.text}
            </span>
          )}
          <div style={{ marginTop: 14 }}>
            <div style={{ fontSize: 11.5, color: 'rgba(255,255,255,0.55)', letterSpacing: '.06em', textTransform: 'uppercase', fontWeight: 500, marginBottom: 6 }}>Net 30j</div>
            <div style={{ fontSize: 36, fontWeight: 700, letterSpacing: '-.025em', color: net >= 0 ? '#86efac' : '#fda4af', lineHeight: 1 }}>
              {tradesLoading ? '—' : fmtMoney(net, true)}
            </div>
          </div>
          <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', marginTop: 16, paddingTop: 14, borderTop: '1px solid rgba(255,255,255,0.10)' }}>
            {[
              { c: 'PARIS', t: par, on: marketOpenCME },
              { c: 'LONDRES', t: ldn, on: sessions.london },
              { c: 'NY', t: ny, on: sessions.newyork },
            ].map(s => (
              <div key={s.c} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                <span style={{ fontSize: 9.5, fontWeight: 600, letterSpacing: '.06em', color: 'rgba(255,255,255,0.55)' }}>{s.c}</span>
                <span className="mono" style={{ fontSize: 11.5, color: '#fff' }}>{s.t.slice(0, 5)}</span>
                <span style={{ width: 5, height: 5, borderRadius: '50%', background: s.on ? '#22c55e' : 'rgba(248,113,113,0.55)' }}></span>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div onClick={goStatsTrading} className={goStatsTrading ? 'tap' : ''} style={{ padding: '0 20px 14px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, cursor: goStatsTrading ? 'pointer' : 'default' }}>
        <QuickStat label="Win Rate" value={stats.winRate || 0} decimals={1} suffix="%" sub={`${stats.wins}W · ${stats.losses}L`}/>
        <QuickStat label="R-moyen" value={stats.avgR || 0} decimals={2} suffix="R" sub={`${stats.count} trade${stats.count > 1 ? 's' : ''}`}/>
      </div>

      <div style={{ padding: '8px 20px 14px' }}>
        <div className="card" style={{ padding: '16px 18px' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 12 }}>
            <span style={{ fontSize: 14, fontWeight: 600 }}>Agenda du jour</span>
            <button onClick={() => nav('routines')} className="tap" style={{ background: 'transparent', border: 'none', color: 'var(--blue-600)', fontSize: 11.5, fontWeight: 500, cursor: 'pointer' }}>Modifier ›</button>
          </div>
          {agenda.length === 0 ? (
            <div style={{ fontSize: 12, color: 'var(--fg-3)', padding: '8px 0' }}>Aucun événement aujourd'hui — ajoute-en depuis Routines.</div>
          ) : (
            <AgendaTimeline now={t} agenda={agenda} toggleAgenda={toggleAgenda}/>
          )}
        </div>
      </div>

      <div style={{ padding: '0 20px 14px' }}>
        <div className="card" style={{ padding: '16px 18px' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 12 }}>
            <span style={{ fontSize: 14, fontWeight: 600 }}>Habitudes</span>
            <button onClick={() => nav('routines')} className="tap" style={{ background: 'transparent', border: 'none', color: 'var(--blue-600)', fontSize: 11.5, fontWeight: 500, cursor: 'pointer' }}>Modifier ›</button>
          </div>
          <HabitsList habits={habits} toggleHabit={toggleHabit}/>
        </div>
      </div>

      <div style={{ padding: '0 20px 18px' }}>
        <div className="card" style={{ padding: '16px 18px' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 12 }}>
            <span style={{ fontSize: 14, fontWeight: 600 }}>Trades récents</span>
            <button onClick={() => openImport && openImport()} className="tap" style={{ background: 'transparent', border: 'none', color: 'var(--blue-600)', fontSize: 11.5, fontWeight: 500, cursor: 'pointer' }}>+ Nouveau</button>
          </div>
          {tradesLoading ? (
            <div style={{ fontSize: 12, color: 'var(--fg-3)', padding: '8px 0' }}>Chargement…</div>
          ) : recent.length === 0 ? (
            <div style={{ fontSize: 12, color: 'var(--fg-3)', padding: '8px 0' }}>
              Aucun trade pour l'instant — importe ton premier CSV ou ajoute un trade manuellement.
            </div>
          ) : recent.map((t, i) => (
            <div key={t.id} onClick={() => openTrade && openTrade(t)} className="tap" style={{
              display: 'grid', gridTemplateColumns: '30px 1fr 80px',
              padding: '10px 0', borderTop: i ? '1px solid var(--line)' : 'none', alignItems: 'center', gap: 8, cursor: 'pointer',
            }}>
              <div style={{ width: 24, height: 24, borderRadius: 6, background: 'var(--bg-elev)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 9, fontWeight: 700, color: 'var(--fg-2)' }}>{(t.symbol || '').slice(0, 2)}</div>
              <div>
                <div style={{ fontSize: 13, fontWeight: 600 }}>{t.symbol} · <span style={{ color: 'var(--fg-3)', fontWeight: 500 }}>{t.setup || '—'}</span></div>
                <div style={{ fontSize: 10.5, color: 'var(--fg-3)', marginTop: 2 }}>{fmtShortDate(t.executed_at)}</div>
              </div>
              <span className={'num ' + ((t.pnl || 0) >= 0 ? 'pos' : 'neg')} style={{ fontSize: 14, fontWeight: 600, textAlign: 'right' }}>{fmtMoney(t.pnl, true)}</span>
            </div>
          ))}
        </div>
      </div>

      <div style={{ padding: '0 20px 18px' }}>
        <div className="card" style={{ padding: '16px 18px' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 12 }}>
            <span style={{ fontSize: 14, fontWeight: 600 }}>{newsTitle}</span>
            <span style={{ fontSize: 11, color: 'var(--fg-3)' }}>{news.length || 4} sources</span>
          </div>
          {news.length === 0 ? (
            [0, 1, 2].map(i => (
              <div key={i} style={{ padding: '9px 0', borderTop: i ? '1px solid var(--line)' : 'none' }}>
                <span style={{ display: 'inline-block', width: 50, height: 8, background: 'var(--bg-elev)', borderRadius: 4, marginBottom: 6 }}></span>
                <span style={{ display: 'block', width: '92%', height: 11, background: 'var(--bg-elev)', borderRadius: 4 }}></span>
              </div>
            ))
          ) : news.slice(0, 6).map((n, i) => (
            <a key={i} href={n.link || '#'} target="_blank" rel="noopener noreferrer" className="tap" style={{
              display: 'block', padding: '9px 0', borderTop: i ? '1px solid var(--line)' : 'none',
              textDecoration: 'none', color: 'inherit',
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 3 }}>
                <span style={{ fontSize: 9.5, fontWeight: 600, letterSpacing: '.08em', color: 'var(--blue-600)' }}>{(n.source || '').toUpperCase()}</span>
                {n.time && <span className="mono" style={{ fontSize: 9.5, color: 'var(--fg-3)' }}>{n.time}</span>}
              </div>
              <div style={{ fontSize: 12.5, lineHeight: 1.4, color: 'var(--fg)' }}>{n.headline}</div>
            </a>
          ))}
        </div>
      </div>
    </div>
  );
}

function DashboardMobile({ state }) {
  const { stats, tradesLoading } = state;
  return (
    <div style={{ padding: '14px 20px 20px' }}>
      <h1 style={{ fontSize: 24, fontWeight: 700, letterSpacing: '-.025em', margin: '0 0 16px' }}>Dashboard</h1>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 14 }}>
        <KpiCard label="Profit Factor" main={stats.count === 0 ? '—' : !Number.isFinite(stats.profitFactor) ? '∞' : <AnimatedNumber value={stats.profitFactor} decimals={2}/>} sub={stats.count > 0 ? `${stats.count} trades` : 'Aucun trade'}/>
        <KpiCard label="Win Rate" main={<AnimatedNumber value={stats.winRate || 0} decimals={1} suffix="%"/>} sub={`${stats.wins}W · ${stats.losses}L`}/>
      </div>
      <div className="card" style={{ padding: '20px 16px', textAlign: 'center' }}>
        {tradesLoading ? (
          <div style={{ fontSize: 12, color: 'var(--fg-3)' }}>Chargement…</div>
        ) : stats.count === 0 ? (
          <div>
            <div style={{ fontSize: 14, color: 'var(--fg-2)', marginBottom: 6 }}>Pas encore de données</div>
            <div style={{ fontSize: 12, color: 'var(--fg-3)' }}>Importe ton premier trade pour voir tes stats.</div>
          </div>
        ) : (
          <div>
            <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 8 }}>Net P&L</div>
            <div className="num" style={{ fontSize: 30, fontWeight: 700, color: stats.netPnl >= 0 ? 'var(--green)' : 'var(--red)' }}>
              {fmtMoney(stats.netPnl, true)}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

function TradesMobile({ openJournal, openImport, openTrade, state }) {
  const { trades, tradesLoading } = state;
  return (
    <div style={{ padding: '14px 20px 20px' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
        <h1 style={{ fontSize: 24, fontWeight: 700, letterSpacing: '-.025em', margin: 0 }}>Trades</h1>
        <button onClick={openImport} className="btn btn-blue tap" style={{ fontSize: 12 }}>{Ico.plus} Nouveau</button>
      </div>
      <div className="card" style={{ padding: '14px 16px' }}>
        {tradesLoading ? (
          <div style={{ fontSize: 12, color: 'var(--fg-3)', padding: '12px 0' }}>Chargement…</div>
        ) : trades.length === 0 ? (
          <div style={{ textAlign: 'center', padding: '40px 0' }}>
            <div style={{ fontSize: 14, color: 'var(--fg-2)', marginBottom: 6 }}>Aucun trade pour l'instant</div>
            <div style={{ fontSize: 12, color: 'var(--fg-3)', marginBottom: 16 }}>Importe un CSV ou ajoute un trade manuellement.</div>
            <button onClick={openImport} className="btn btn-blue tap">{Ico.plus} Ajouter un trade</button>
          </div>
        ) : trades.map((t, i) => (
          <div key={t.id} onClick={() => openTrade && openTrade(t)} className="tap" style={{
            display: 'grid', gridTemplateColumns: '28px 1fr 80px',
            padding: '12px 0', borderTop: i ? '1px solid var(--line)' : 'none', alignItems: 'center', gap: 10, cursor: 'pointer',
          }}>
            <div style={{ width: 26, height: 26, borderRadius: 6, background: 'var(--bg-elev)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 9.5, fontWeight: 700, color: 'var(--fg-2)' }}>{(t.symbol || '').slice(0, 2)}</div>
            <div>
              <div style={{ fontSize: 13, fontWeight: 600 }}>{t.symbol} · <span style={{ color: 'var(--fg-3)', fontWeight: 500 }}>{t.setup || '—'}</span></div>
              <div style={{ fontSize: 10.5, color: 'var(--fg-3)', marginTop: 2 }}>{fmtShortDate(t.executed_at)}</div>
            </div>
            <span className={'num ' + ((t.pnl || 0) >= 0 ? 'pos' : 'neg')} style={{ fontSize: 14, fontWeight: 600, textAlign: 'right' }}>{fmtMoney(t.pnl, true)}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function DailyMobile({ openJournal, state }) {
  const { tradesByDay, tradesLoading } = state;
  const days = Object.keys(tradesByDay).sort().reverse().slice(0, 30);
  return (
    <div style={{ padding: '14px 20px 20px' }}>
      <h1 style={{ fontSize: 24, fontWeight: 700, letterSpacing: '-.025em', margin: '0 0 16px' }}>Daily Journal</h1>
      {tradesLoading ? (
        <div style={{ fontSize: 12, color: 'var(--fg-3)', padding: '12px 0' }}>Chargement…</div>
      ) : days.length === 0 ? (
        <div className="card" style={{ padding: '24px 18px', textAlign: 'center' }}>
          <div style={{ fontSize: 14, color: 'var(--fg-2)', marginBottom: 6 }}>Pas encore de journaux</div>
          <div style={{ fontSize: 12, color: 'var(--fg-3)' }}>Tes journaux quotidiens apparaîtront ici dès que tu auras des trades.</div>
        </div>
      ) : days.map(day => {
        const data = tradesByDay[day];
        return (
          <div key={day} onClick={() => openJournal && openJournal(day)} className="card tap" style={{ padding: '16px 18px', marginBottom: 10, cursor: 'pointer' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 8 }}>
              <span style={{ fontSize: 14, fontWeight: 600 }}>{fmtLongDate(day)}</span>
              <span className={'num ' + (data.pnl > 0 ? 'pos' : data.pnl < 0 ? 'neg' : '')} style={{ fontSize: 17, fontWeight: 600 }}>
                {fmtMoney(data.pnl, true)}
              </span>
            </div>
            <div style={{ fontSize: 11.5, color: 'var(--fg-3)' }}>{data.trades.length} trade{data.trades.length > 1 ? 's' : ''} · {data.wins}W / {data.losses}L</div>
          </div>
        );
      })}
    </div>
  );
}

// ─── Settings shared bits (profile form + GDPR data actions) ──────────
// TODO: wire timezone into clocks/sessions when multi-region.
const TZ_OPTIONS = [
  { v: 'Europe/Paris', l: 'Europe/Paris' },
  { v: 'Europe/London', l: 'Europe/London' },
  { v: 'America/New_York', l: 'America/New_York' },
  { v: 'America/Chicago', l: 'America/Chicago' },
  { v: 'Asia/Tokyo', l: 'Asia/Tokyo' },
  { v: 'Australia/Sydney', l: 'Australia/Sydney' },
];
const CURRENCY_OPTIONS = [
  { v: 'USD', l: 'USD ($)' },
  { v: 'EUR', l: 'EUR (€)' },
  { v: 'GBP', l: 'GBP (£)' },
];

// Editable profile form. Pre-fills from state.profile, saves via state.saveProfile.
function ProfileForm({ state }) {
  const p = state?.profile || null;
  const [first, setFirst]   = React.useState('');
  const [last, setLast]     = React.useState('');
  const [disp, setDisp]     = React.useState('');
  const [tz, setTz]         = React.useState('Europe/Paris');
  const [cur, setCur]       = React.useState('USD');
  const [saving, setSaving] = React.useState(false);
  const [saved, setSaved]   = React.useState(false);
  const [err, setErr]       = React.useState('');

  // (Re)hydrate inputs whenever the profile row loads/changes.
  React.useEffect(() => {
    setFirst(p?.first_name || '');
    setLast(p?.last_name || '');
    setDisp(p?.display_name || '');
    setTz(p?.timezone || 'Europe/Paris');
    setCur(p?.currency || 'USD');
  }, [p]);

  // Clear the "Enregistré ✓" badge after 2s.
  React.useEffect(() => {
    if (!saved) return;
    const id = setTimeout(() => setSaved(false), 2000);
    return () => clearTimeout(id);
  }, [saved]);

  const onSave = async () => {
    if (saving) return;
    setSaving(true); setErr('');
    const patch = {
      first_name: first.trim() || null,
      last_name: last.trim() || null,
      display_name: disp.trim() || null,
      timezone: tz,
      currency: cur,
    };
    const r = await state.saveProfile(patch);
    setSaving(false);
    if (r && r.error) {
      const raw = String(r.error.message || '');
      // Never surface raw English DB errors to users — map to clean French.
      const msg = /schema cache|public\.profiles|does not exist|relation/i.test(raw)
        ? 'Profil temporairement indisponible. Réessaie dans un instant.'
        : 'Impossible d\'enregistrer. Vérifie ta connexion et réessaie.';
      setErr(msg);
      return;
    }
    setSaved(true);
  };

  const labelStyle = { fontSize: 11, fontWeight: 600, color: 'var(--fg-3)', letterSpacing: '.04em', textTransform: 'uppercase', marginBottom: 6, display: 'block' };
  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 12 }}>
        <div>
          <label style={labelStyle}>Prénom</label>
          <input className="input" value={first} onChange={e => setFirst(e.target.value)} placeholder="Alex"/>
        </div>
        <div>
          <label style={labelStyle}>Nom</label>
          <input className="input" value={last} onChange={e => setLast(e.target.value)} placeholder="Martin"/>
        </div>
      </div>
      <div style={{ marginBottom: 12 }}>
        <label style={labelStyle}>Pseudo affiché</label>
        <input className="input" value={disp} onChange={e => setDisp(e.target.value)} placeholder="Utilisé pour te saluer sur l'accueil"/>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 16 }}>
        <div>
          <label style={labelStyle}>Fuseau horaire</label>
          <select className="input" value={tz} onChange={e => setTz(e.target.value)}>
            {TZ_OPTIONS.map(o => <option key={o.v} value={o.v}>{o.l}</option>)}
          </select>
        </div>
        <div>
          <label style={labelStyle}>Devise</label>
          <select className="input" value={cur} onChange={e => setCur(e.target.value)}>
            {CURRENCY_OPTIONS.map(o => <option key={o.v} value={o.v}>{o.l}</option>)}
          </select>
        </div>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <button onClick={onSave} disabled={saving} className="btn btn-blue tap" style={{ opacity: saving ? 0.6 : 1 }}>
          {saving ? 'Enregistrement…' : 'Enregistrer'}
        </button>
        {saved && <span style={{ fontSize: 12.5, color: 'var(--green)', fontWeight: 600 }}>Enregistré ✓</span>}
        {err && <span style={{ fontSize: 12.5, color: 'var(--red)' }}>{err}</span>}
      </div>
    </div>
  );
}

// Type-to-confirm destructive action. The user must type `word` exactly before
// the confirm button enables. On confirm, runs onConfirm() (async, returns
// {error}|{ok}); a successful onConfirm is expected to navigate/reload.
function TypeToConfirm({ word, confirmLabel, color, onConfirm }) {
  const [open, setOpen] = React.useState(false);
  const [val, setVal]   = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [err, setErr]   = React.useState('');
  const c = color || 'var(--red)';
  const armed = val.trim().toUpperCase() === word;

  const reset = () => { setOpen(false); setVal(''); setErr(''); };

  const run = async () => {
    if (!armed || busy) return;
    setBusy(true); setErr('');
    const r = await onConfirm();
    if (r && r.error) { setBusy(false); setErr(r.error.message || 'Une erreur est survenue.'); return; }
    // Success: caller's onConfirm is expected to navigate/reload. Keep the
    // spinner up so the UI doesn't flash an enabled state during reload.
  };

  if (!open) {
    return (
      <button onClick={() => setOpen(true)} className="btn tap" style={{ color: c, borderColor: c }}>{confirmLabel}</button>
    );
  }
  return (
    <div>
      <div style={{ fontSize: 12, color: 'var(--fg-2)', marginBottom: 8 }}>
        Tape <b style={{ color: c }}>{word}</b> pour confirmer.
      </div>
      <input
        className="input" value={val} onChange={e => setVal(e.target.value)}
        placeholder={word} autoFocus disabled={busy}
        style={{ marginBottom: 10 }}
      />
      <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
        <button onClick={run} disabled={!armed || busy} className="btn tap"
          style={{ background: armed ? c : 'var(--bg-elev)', color: armed ? '#fff' : 'var(--fg-4)', borderColor: armed ? c : 'var(--line)', cursor: armed && !busy ? 'pointer' : 'not-allowed', opacity: busy ? 0.7 : 1 }}>
          {busy ? 'Traitement…' : confirmLabel}
        </button>
        <button onClick={reset} disabled={busy} className="btn tap">Annuler</button>
        {err && <span style={{ fontSize: 12, color: 'var(--red)' }}>{err}</span>}
      </div>
    </div>
  );
}

// The two GDPR data actions (reset journal + delete account), shared desktop/mobile.
function DataActions() {
  const resetJournal = async () => {
    if (typeof window.resetMyData !== 'function') return { error: { message: 'Module indisponible — recharge la page.' } };
    const r = await window.resetMyData();
    if (r && r.error) return r;
    window.location.reload(); // re-fetch empty state
    return { ok: true };
  };
  const deleteAccount = async () => {
    if (typeof window.deleteMyAccount !== 'function') return { error: { message: 'Module indisponible — recharge la page.' } };
    const r = await window.deleteMyAccount();
    if (r && r.error) return r;
    window.location.reload(); // back to login screen
    return { ok: true };
  };
  return (
    <React.Fragment>
      <div className="card" style={{ padding: '20px 22px', marginBottom: 14, borderColor: 'var(--orange)' }}>
        <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 4, color: 'var(--orange)' }}>Réinitialiser mon journal</div>
        <div style={{ fontSize: 12, color: 'var(--fg-3)', marginBottom: 14 }}>
          Efface tous tes trades, habitudes, agenda, notes, captures, stratégies et sessions de backtest. Ton compte est conservé.
        </div>
        <TypeToConfirm word="RESET" confirmLabel="Réinitialiser mon journal" color="var(--orange)" onConfirm={resetJournal}/>
      </div>

      <div className="card" style={{ padding: '20px 22px', borderColor: 'var(--red-soft)' }}>
        <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 4, color: 'var(--red)' }}>Supprimer le compte</div>
        <div style={{ fontSize: 12, color: 'var(--fg-3)', marginBottom: 14 }}>
          Supprime définitivement toutes tes données personnelles et te déconnecte. Cette action est irréversible.
        </div>
        <TypeToConfirm word="SUPPRIMER" confirmLabel="Supprimer définitivement" color="var(--red)" onConfirm={deleteAccount}/>
        <div style={{ fontSize: 11, color: 'var(--fg-4)', marginTop: 12, lineHeight: 1.5 }}>
          L'enregistrement d'authentification résiduel (email) peut être purgé sur demande à support@tempo.app.
        </div>
      </div>
    </React.Fragment>
  );
}

function SettingsMobile({ state, onLogout, openImport, nav }) {
  const email = state?.user?.email || '';
  return (
    <div style={{ padding: '14px 20px 28px' }}>
      <h1 style={{ fontSize: 24, fontWeight: 700, letterSpacing: '-.025em', margin: '0 0 16px' }}>Plus</h1>

      {/* Accès mobile à l'analyse fondamentale : la route n'existe pas dans la barre du bas,
          on l'expose donc ici en tête de l'onglet « Plus ». */}
      {typeof nav === 'function' && (
        <React.Fragment>
          <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--fg-2)', marginBottom: 10 }}>Marchés</div>
          <button
            className="card tap lift"
            onClick={() => nav('fondamental')}
            style={{
              width: '100%', textAlign: 'left', cursor: 'pointer',
              padding: '14px 16px', marginBottom: 22,
              display: 'flex', alignItems: 'center', gap: 12,
              borderColor: 'var(--blue-border)',
            }}
          >
            <span style={{
              width: 38, height: 38, borderRadius: 11, flexShrink: 0,
              background: 'var(--blue-soft)', color: 'var(--blue-600)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>{Ico.fondamental}</span>
            <span style={{ flex: 1, minWidth: 0 }}>
              <span style={{ display: 'block', fontSize: 14.5, fontWeight: 700, color: 'var(--fg)', letterSpacing: '-.015em' }}>Analyse fondamentale</span>
              <span style={{ display: 'block', fontSize: 12, color: 'var(--fg-3)', marginTop: 2 }}>Contexte macro : biais, catalyseurs et actualités</span>
            </span>
            <svg className="ico" width="16" height="16" viewBox="0 0 20 20" style={{ color: 'var(--fg-4)', flexShrink: 0 }} aria-hidden="true"><path d="M7.5 5l5 5-5 5"/></svg>
          </button>
        </React.Fragment>
      )}

      <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--fg-2)', marginBottom: 10 }}>Profil</div>
      <div className="card" style={{ padding: '16px 18px', marginBottom: 22 }}>
        <ProfileForm state={state}/>
      </div>

      <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--fg-2)', marginBottom: 10 }}>Compte</div>
      <div className="card" style={{ padding: '16px 18px', marginBottom: 12 }}>
        <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--fg-3)', letterSpacing: '.06em', textTransform: 'uppercase', marginBottom: 6 }}>Email</div>
        <div style={{ fontSize: 14, color: 'var(--fg)' }}>{email || '—'}</div>
      </div>
      <div className="card" style={{ padding: '16px 18px', marginBottom: 12 }}>
        <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 4 }}>Mot de passe</div>
        <div style={{ fontSize: 12, color: 'var(--fg-3)', marginBottom: 14 }}>Change le mot de passe de connexion de ton compte.</div>
        {typeof window.PasswordForm === 'function'
          ? <window.PasswordForm/>
          : <div style={{ fontSize: 12, color: 'var(--fg-3)' }}>Module indisponible — recharge la page.</div>}
      </div>
      <div className="card" style={{ padding: '16px 18px', marginBottom: 22 }}>
        <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 4 }}>Déconnexion</div>
        <div style={{ fontSize: 12, color: 'var(--fg-3)', marginBottom: 14 }}>Tu pourras te reconnecter avec ton email à tout moment.</div>
        <button onClick={onLogout} className="btn tap">Se déconnecter</button>
      </div>

      <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--fg-2)', marginBottom: 10 }}>Brokers</div>
      <div style={{ marginBottom: 22 }}>
        {typeof window.BrokerPanelCompact === 'function'
          ? <BrokerPanelCompact onSynced={state.refreshTrades} openImport={openImport}/>
          : <div className="card" style={{ padding: '16px 18px', fontSize: 12, color: 'var(--fg-3)' }}>Module broker indisponible — recharge la page.</div>}
      </div>

      <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--fg-2)', marginBottom: 10 }}>Données</div>
      <DataActions/>

      <div style={{ marginTop: 22, display: 'flex', flexDirection: 'column', gap: 6, alignItems: 'center' }}>
        {typeof window.TradingDisclaimer === 'function' && <window.TradingDisclaimer compact/>}
        {typeof window.LegalLinks === 'function' && <window.LegalLinks compact/>}
      </div>
    </div>
  );
}

function SettingsPage({ state, onLogout, openImport }) {
  const email = state?.user?.email || '';
  return (
    <div className="scroll" style={{ width: '100%', height: '100%', overflow: 'auto' }}>
      <PageHeader title="Réglages"/>
      <div style={{ padding: '24px 24px 40px', maxWidth: 720 }}>
        <h2 style={{ fontSize: 19, fontWeight: 700, letterSpacing: '-.02em', margin: 0, marginBottom: 4 }}>Profil</h2>
        <p style={{ fontSize: 13, color: 'var(--fg-2)', marginTop: 4, marginBottom: 18 }}>Tes informations personnelles.</p>

        <div className="card" style={{ padding: '20px 22px', marginBottom: 28 }}>
          <ProfileForm state={state}/>
        </div>

        <h2 style={{ fontSize: 19, fontWeight: 700, letterSpacing: '-.02em', margin: 0, marginBottom: 4 }}>Compte</h2>
        <p style={{ fontSize: 13, color: 'var(--fg-2)', marginTop: 4, marginBottom: 18 }}>Gère ton compte Tempo.</p>

        <div className="card" style={{ padding: '20px 22px', marginBottom: 14 }}>
          <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--fg-3)', letterSpacing: '.06em', textTransform: 'uppercase', marginBottom: 6 }}>Email</div>
          <div style={{ fontSize: 14, color: 'var(--fg)', marginBottom: 4 }}>{email || '—'}</div>
          <div style={{ fontSize: 11.5, color: 'var(--fg-3)' }}>Ton identifiant de connexion.</div>
        </div>

        <div className="card" style={{ padding: '20px 22px', marginBottom: 14 }}>
          <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 4 }}>Mot de passe</div>
          <div style={{ fontSize: 12, color: 'var(--fg-3)', marginBottom: 14 }}>Change le mot de passe de connexion de ton compte.</div>
          <div style={{ maxWidth: 380 }}>
            {typeof window.PasswordForm === 'function'
              ? <window.PasswordForm/>
              : <div style={{ fontSize: 12, color: 'var(--fg-3)' }}>Module indisponible — recharge la page.</div>}
          </div>
        </div>

        <div className="card" style={{ padding: '20px 22px', marginBottom: 28 }}>
          <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 4 }}>Déconnexion</div>
          <div style={{ fontSize: 12, color: 'var(--fg-3)', marginBottom: 14 }}>Tu pourras te reconnecter avec ton email à tout moment.</div>
          <button onClick={onLogout} className="btn tap">Se déconnecter</button>
        </div>

        <h2 style={{ fontSize: 19, fontWeight: 700, letterSpacing: '-.02em', margin: 0, marginBottom: 4 }}>Brokers &amp; synchronisation</h2>
        <p style={{ fontSize: 13, color: 'var(--fg-2)', marginTop: 4, marginBottom: 18 }}>Connecte ton broker pour importer tes trades automatiquement, ou importe un fichier.</p>

        <div style={{ marginBottom: 28 }}>
          {typeof window.BrokerPanel === 'function'
            ? <BrokerPanel onSynced={state.refreshTrades} openImport={openImport}/>
            : <div className="card" style={{ padding: '20px 22px', fontSize: 13, color: 'var(--fg-3)' }}>Module broker indisponible — recharge la page.</div>}
        </div>

        <h2 style={{ fontSize: 19, fontWeight: 700, letterSpacing: '-.02em', margin: 0, marginBottom: 4 }}>Données</h2>
        <p style={{ fontSize: 13, color: 'var(--fg-2)', marginTop: 4, marginBottom: 18 }}>Réinitialise ton journal ou supprime ton compte.</p>

        <DataActions/>

        <div style={{ marginTop: 26, display: 'flex', flexDirection: 'column', gap: 6, alignItems: 'center' }}>
          {typeof window.TradingDisclaimer === 'function' && <window.TradingDisclaimer compact/>}
          {typeof window.LegalLinks === 'function' && <window.LegalLinks compact/>}
        </div>
      </div>
    </div>
  );
}

// ─── Number/date formatting helpers ───────────────────────────────
// Point d'injection UNIQUE de la devise. On délègue à fmtMoneyCur (format-prefs.jsx)
// en lisant la devise du profil propagée dans window.__appCurrency par state.jsx.
// Tous les consommateurs (dashboard, stats, home, weekly, daily) héritent ainsi
// automatiquement de la devise choisie en Réglages. Fallback inline si le module
// format-prefs n'est pas (encore) chargé, en conservant l'ancien rendu en dollars.
function fmtMoney(v, sign = false) {
  const cur = (typeof window !== 'undefined' && window.__appCurrency) || 'USD';
  if (typeof fmtMoneyCur === 'function') return fmtMoneyCur(v, cur, sign);
  // Fallback historique (devise non disponible → $).
  const n = Number(v) || 0;
  const a = Math.abs(n);
  const formatted = a.toLocaleString('fr-FR', { minimumFractionDigits: a < 100 ? 2 : 0, maximumFractionDigits: 2 });
  if (n === 0) return '$0,00';
  const prefix = sign ? (n > 0 ? '+$' : '−$') : '$';
  return prefix + formatted;
}

function fmtShortDate(iso) {
  if (!iso) return '—';
  const d = new Date(iso);
  if (isNaN(d.getTime())) return '—';
  const mm = ['janv.', 'févr.', 'mars', 'avril', 'mai', 'juin', 'juil.', 'août', 'sept.', 'oct.', 'nov.', 'déc.'];
  return `${d.getDate()} ${mm[d.getMonth()]} · ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
}

function fmtLongDate(iso) {
  if (!iso) return '—';
  const d = new Date(iso.length === 10 ? iso + 'T00:00:00' : iso);
  if (isNaN(d.getTime())) return iso;
  const days = ['Dim.', 'Lun.', 'Mar.', 'Mer.', 'Jeu.', 'Ven.', 'Sam.'];
  const mm = ['janv.', 'févr.', 'mars', 'avril', 'mai', 'juin', 'juil.', 'août', 'sept.', 'oct.', 'nov.', 'déc.'];
  return `${days[d.getDay()]} ${d.getDate()} ${mm[d.getMonth()]}`;
}

Object.assign(window, { fmtMoney, fmtShortDate, fmtLongDate, buildISOFromDay });

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