/* ─────────────────────────────────────────────────────────
   app.jsx — main dashboard composition + Tweaks integration
   ───────────────────────────────────────────────────────── */

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "todayState": "auto",
  "density": "regular",
  "logo": "candlesticks"
}/*EDITMODE-END*/;

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [selectedAcct, setSelectedAcct] = React.useState(0);
  const D = window.DATA;
  const acct = D.accounts[selectedAcct];
  const clock = useETClock();

  // Inject the active account's accent into a CSS var so the chart line / fill follow
  document.documentElement.style.setProperty("--acct-accent", acct.accentColor);

  // Decide which "today" plan to show. Tweak takes precedence (for demo + testing).
  // When tweak is "auto" we let the market clock pick: after-hours + a closed
  // trade-day → show tomorrow's plan; weekends → show the weekend plan.
  const resolvedState = (() => {
    if (t.todayState !== "auto") return t.todayState;
    if (clock.parts.weekday === "Sat" || clock.parts.weekday === "Sun") return "weekend";
    // Weekday: after 16:00 ET (market closed) shows tomorrow's plan
    if (clock.status.isAfterHours) return "next_day";
    // Pre-market hours: queued
    if (clock.parts.totalMin < 570) return "pre_market";
    // 10:45 – 13:00 ET = bot is holding; outside that during open hours show closed-state
    if (clock.parts.totalMin >= 645 && clock.parts.totalMin < 780) return "holding";
    return "closed";
  })();

  const plan = (() => {
    const base = acct.todayPlans[resolvedState] || acct.todayPlans.closed;
    // For next_day, embed today's settled result so the hero can surface it
    if (resolvedState === "next_day") {
      const today = acct.todayPlans.closed;
      return {
        ...base,
        today_settled: {
          ticker: today.ticker,
          ticker_long: today.ticker_long,
          buy_time: today.buy_time,
          sell_time: today.sell_time,
          buy_price: today.buy_price,
          sell_price: today.sell_price,
          shares: today.shares,
          realized_pnl: today.realized_pnl,
          realized_pnl_pct: today.realized_pnl_pct,
        },
      };
    }
    return base;
  })();
  const equitySpark = acct.equityCurve.slice(-15).map(d => d.portfolio_value);

  // Account/position visibility: no_trade / weekend / next_day zeros out today's P&L + positions
  const flatState = ["no_trade", "weekend", "next_day"].includes(resolvedState);
  const account = flatState
    ? { ...acct.account, day_pnl_dollars: 0, open_positions_count: 0 }
    : resolvedState === "holding"
      ? { ...acct.account, open_positions_count: 1 }
      : acct.account;

  const shellStyle = t.density === "compact"
    ? { padding: "20px 32px 56px" }
    : {};

  return (
    <div className="app">
      <div className="shell" style={shellStyle}>
        <Topbar botHealth={D.botHealth} asOf={D.asOf} clock={clock} logoVariant={t.logo} />

        <AccountTabs
          accounts={D.accounts}
          selected={selectedAcct}
          onSelect={setSelectedAcct}
        />

        <TodayHero
          plan={plan}
          account={account}
          streakHistory={acct.streakHistory}
          currentStreak={acct.currentStreak}
          botHealth={D.botHealth}
          equitySpark={equitySpark}
          asOf={D.asOf}
          acct={acct}
          clock={clock}
        />

        <section className="section">
          <div className="section-head">
            <div>
              <div className="section-label">Performance</div>
              <h2 className="section-title">Is this strategy actually making money?</h2>
            </div>
            <div className="section-meta">window · 35 trading days · since Mar 31</div>
          </div>
          <StatsRow perf={acct.perf} />
          <MainChart
            equityCurve={acct.equityCurve}
            dailyPnl={acct.dailyPnl}
            tradeByDate={acct.tradeByDate}
            tickerMeta={D.tickerMeta}
            accentColor={acct.accentColor}
          />
          <TradesTable trades={acct.recentTrades} tickerMeta={D.tickerMeta} />
        </section>

        <AboutSection strategy={acct.strategy} acct={acct} />

        <footer className="foot">
          <div>thetradingoptimizer.com / daily-runner</div>
          <div>v0.1 · alpaca · {new Date().getFullYear()}</div>
        </footer>
      </div>

      <TweaksPanel title="Tweaks">
        <TweakSection label="Logo" />
        <TweakSelect
          label="Variant"
          value={t.logo}
          onChange={v => setTweak("logo", v)}
          options={[
            { value: "candlesticks", label: "Candlesticks + arrow" },
            { value: "monogram",    label: "Monogram tile (tO)" },
            { value: "ticker",      label: "$TO ticker chip" },
            { value: "target",      label: "Target / crosshair" },
            { value: "network",     label: "Network constellation" },
            { value: "bracket",     label: "Bracketed schedule" },
          ]}
        />
        <TweakSection label="Today's state" />
        <TweakSelect
          label="Scenario"
          value={t.todayState}
          onChange={v => setTweak("todayState", v)}
          options={[
            { value: "auto",       label: "Auto (follow ET clock)" },
            { value: "closed",     label: "Closed (today, real log)" },
            { value: "holding",    label: "Holding (mid-trade)" },
            { value: "pre_market", label: "Pre-market (queued)" },
            { value: "next_day",   label: "After-hours · tomorrow" },
            { value: "no_trade",   label: "No trade today" },
            { value: "weekend",    label: "Weekend / closed" },
          ]}
        />
        <TweakSection label="Density" />
        <TweakRadio
          label="Padding"
          value={t.density}
          onChange={v => setTweak("density", v)}
          options={[
            { value: "regular", label: "Regular" },
            { value: "compact", label: "Compact" },
          ]}
        />
      </TweaksPanel>
    </div>
  );
}

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