// TitratePlan — main app

const { useState, useEffect, useMemo } = React;

const ARTICLE_ROUTES = {
  "site-rotation": { component: "SiteRotationGuide", title: "Injection site rotation" },
  "titration":     { component: "HowTitrationWorks", title: "How GLP-1 titration is typically described" },
  "missed-dose":   { component: "MissedDose",        title: "If you miss a dose" },
  "storage":       { component: "StorageTravel",     title: "Storage & travel" },
  "about":         { component: "About",             title: "About TitratePlan" },
  "privacy":       { component: "Privacy",           title: "Privacy" },
  "advertising":   { component: "AdvertisingDisclosure", title: "Advertising disclosure" },
};

function useHashRoute() {
  const get = () => (typeof window !== "undefined" ? window.location.hash.replace(/^#\/?/, "") : "");
  const [hash, setHash] = useState(get());
  useEffect(() => {
    const handler = () => {
      setHash(get());
      // Routed pages should scroll to top; in-page anchors handle themselves
      if (ARTICLE_ROUTES[get()]) {
        window.scrollTo({ top: 0, behavior: "instant" in window ? "instant" : "auto" });
      }
    };
    window.addEventListener("hashchange", handler);
    return () => window.removeEventListener("hashchange", handler);
  }, []);
  return hash;
}

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "light",
  "showAds": true,
  "showAffiliate": true,
  "showSiteRotation": true,
  "calendarDensity": "comfortable"
}/*EDITMODE-END*/;

function todayISO() {
  const d = new Date();
  return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,"0")}-${String(d.getDate()).padStart(2,"0")}`;
}

function HeroPreview() {
  return (
    <div className="hero-visual">
      <img src="uploads/bullet_points.png" alt="Generated 100% in your browser. Stored 100% on your device — no account needed. Calendar export format: .ics — universal. Totally free, always and forever." className="hero-img" />
    </div>
  );
}

function App() {
  const [tweaks, setTweak] = window.useTweaks(TWEAK_DEFAULTS);

  const [setupValue, setSetupValue] = useState({
    scheduleId: "semaglutide_weight",
    startDate: window.isoDate(new Date()),
    injectionDow: 1,
    maintenanceWeeks: 26,
    includeReminders: true,
    rotateSites: true,
    enabledSites: window.DEFAULT_SITES,
    startSite: window.DEFAULT_SITES[0],
    customStepOverrides: null,   // null = use manufacturer defaults; otherwise array of {weeks, doseMg} matching schedule steps
  });
  const [activePlan, setActivePlan] = useState(null);
  const [anchorDate, setAnchorDate] = useState(new Date());
  const [showCustomConfirm, setShowCustomConfirm] = useState(false);
  const [pendingCustomization, setPendingCustomization] = useState(null);

  // Apply theme
  useEffect(() => {
    document.body.dataset.theme = tweaks.theme;
  }, [tweaks.theme]);

  // Auto-generate the demo plan on first load so the page isn't empty
  useEffect(() => {
    handleGenerate(setupValue);
    // eslint-disable-next-line
  }, []);

  function handleGenerate(v) {
    // Use the start-date's DOW as the injection cadence (no separate dropdown).
    const startObj = new Date(v.startDate + "T00:00:00");
    let customSteps = null;
    if (v.customStepOverrides && Array.isArray(v.customStepOverrides) && v.customStepOverrides.length > 0) {
      const lastIdx = v.customStepOverrides.length - 1;
      customSteps = v.customStepOverrides.map((o, i) => ({
        weeks: Number.isFinite(o.weeks) && o.weeks > 0 ? o.weeks : 4,
        doseMg: Number.isFinite(o.doseMg) && o.doseMg > 0 ? o.doseMg : 0.25,
        label: o.label || (i === lastIdx ? "Maintenance" : `Step ${i + 1}`),
        isMaintenance: i === lastIdx,
      }));
    }
    // Effective stepset (custom overrides or manufacturer defaults).
    const effectiveSteps = customSteps || (window.GLP1_SCHEDULES[v.scheduleId]?.steps || []);
    // Titration weeks = sum of weeks for every non-maintenance step.
    const titrationWeeks = effectiveSteps
      .filter(s => !s.isMaintenance)
      .reduce((sum, s) => sum + (Number.isFinite(s.weeks) && s.weeks > 0 ? s.weeks : 4), 0);
    const totalWeeks = titrationWeeks + (Number.isFinite(v.maintenanceWeeks) && v.maintenanceWeeks >= 0 ? v.maintenanceWeeks : 26);
    const events = window.buildDoseEvents({
      scheduleId: v.scheduleId,
      startDateISO: v.startDate,
      injectionDow: startObj.getDay(),
      weeksToInclude: totalWeeks,
      customSteps,
    });
    if (v.rotateSites) {
      const enabled = (v.enabledSites && v.enabledSites.length) ? v.enabledSites : window.DEFAULT_SITES;
      const startIdx = Math.max(0, enabled.indexOf(v.startSite));
      events.forEach((e, i) => { e.site = enabled[(startIdx + i) % enabled.length]; });
    } else {
      events.forEach(e => { e.site = null; });
    }
    const baseSchedule = window.GLP1_SCHEDULES[v.scheduleId];
    const schedule = customSteps
      ? { ...baseSchedule, steps: customSteps }
      : baseSchedule;
    setActivePlan({ schedule, events, includeReminders: v.includeReminders, rotateSites: v.rotateSites });
    // Anchor the calendar to the plan start (or today, whichever is later) so users see their schedule
    const start = new Date(v.startDate);
    const today = new Date();
    setAnchorDate(start > today ? start : today);
  }

  const computed = useMemo(() => {
    if (!activePlan) return null;
    const { events, schedule } = activePlan;
    const today = new Date();
    const todayMid = new Date(today.getFullYear(), today.getMonth(), today.getDate());

    // Most recent past or current event = "current dose"
    let currentIdx = -1;
    for (let i = 0; i < events.length; i++) {
      if (events[i].date <= todayMid) currentIdx = i;
      else break;
    }
    const todayEvent = currentIdx >= 0 ? events[currentIdx] : null;
    const nextEvent = events.find(e => e.date >= todayMid) || null;

    // Next escalation = next event with isFirstOfStep = true and date >= today
    const nextEscalation = events.find(e => e.date > todayMid && e.isFirstOfStep) || null;

    const weeksIn = Math.max(1, currentIdx + 1);
    return { todayEvent, nextEvent, nextEscalation, weeksIn, schedule, events };
  }, [activePlan]);

  const route = useHashRoute();
  const article = ARTICLE_ROUTES[route];

  return (
    <>
      <window.Topbar
        theme={tweaks.theme}
        setTheme={(t) => setTweak("theme", t)}
      />

      {article ? (
        <div className="page article-page">
          <nav className="route-breadcrumb">
            <a href="#" onClick={(e) => { e.preventDefault(); window.location.hash = ""; }}>
              ← Back to planner
            </a>
          </nav>
          {React.createElement(window[article.component])}
        </div>
      ) : (

      <div className="page">
        <section className="hero">
          <div className="hero-top">
            <div>
              <h1 className="serif">
                <span className="line">Your journey.</span>
                <span className="line line-2">Simplified.</span>
              </h1>
              <p className="lede">
                A simple, private way to plan your GLP-1 schedule and track your doses. Build
                a personalized dose-escalation calendar for semaglutide or tirzepatide and
                export every injection to Apple Calendar, Google Calendar, or Outlook in one click.
              </p>
            </div>
            <HeroPreview />
          </div>
        </section>

        {/* Setup + quick log entry */}
        <div className="setup-row">
          <div><window.SetupForm
            value={setupValue}
            onChange={setSetupValue}
            onSubmit={() => handleGenerate(setupValue)}
            hasActivePlan={!!activePlan}
            onReset={() => setActivePlan(null)}
            onRequestCustomize={(nextOverrides) => {
              const acknowledged = (() => {
                try { return localStorage.getItem("titrateplan_custom_ack") === "1"; }
                catch { return false; }
              })();
              if (acknowledged) {
                setSetupValue({ ...setupValue, customStepOverrides: nextOverrides });
              } else {
                setPendingCustomization(nextOverrides);
                setShowCustomConfirm(true);
              }
            }}
          /></div>
          <div><window.QuickLogCard /></div>
          {showCustomConfirm && (
            <window.CustomConfirmModal
              onCancel={() => { setShowCustomConfirm(false); setPendingCustomization(null); }}
              onAccept={() => {
                try { localStorage.setItem("titrateplan_custom_ack", "1"); } catch {}
                setSetupValue({ ...setupValue, customStepOverrides: pendingCustomization });
                setShowCustomConfirm(false);
                setPendingCustomization(null);
              }}
            />
          )}
        </div>

        {/* Leaderboard ad — break between input and the generated schedule */}
        {tweaks.showAds && (
          <div style={{ marginTop: 24 }}>
            <window.AdSlot size="leaderboard" label="728 × 90 leaderboard" />
          </div>
        )}

        {/* Status strip, full width */}
        {computed && (
          <div className="stack-md" style={{ marginTop: 24 }}>
            <window.StatusStrip
              schedule={computed.schedule}
              events={computed.events}
              todayEvent={computed.todayEvent}
              nextEscalation={computed.nextEscalation}
              weeksIn={computed.weeksIn}
            />
          </div>
        )}

        {/* Dose ladder chart */}
        {computed && (
          <div className="stack-md" style={{ marginTop: 24 }}>
            <window.WeeklyBarChart
              schedule={computed.schedule}
              events={computed.events}
              currentEvent={computed.todayEvent}
            />
          </div>
        )}

        {/* Today + Site rotation as a wrapping row */}
        {computed && (
          <div className="focus-row">
            <window.TodayCard
              todayEvent={computed.todayEvent}
              nextEvent={computed.nextEvent}
              schedule={computed.schedule}
            />
            {tweaks.showSiteRotation && activePlan.rotateSites && (
              <window.SiteRotation
                todayEvent={computed.todayEvent}
                nextEvent={computed.nextEvent}
                enabledSites={setupValue.enabledSites}
              />
            )}
          </div>
        )}

        {/* Main grid: calendar + rail */}
        {computed && (
          <>
            <div className="section-h">
              <h2>Your schedule</h2>
              <span className="meta">{computed.events.length} doses · {computed.events.length} weeks total</span>
            </div>
            <div className="main-grid">
              <div className="stack-lg">
                <window.MonthCalendar events={computed.events} anchorDate={anchorDate} setAnchorDate={setAnchorDate} />

                {/* Native ad inline */}
                {tweaks.showAds && (
                  <div className="ad-slot ad-native">
                    <div style={{ fontSize: 9, color: "var(--muted-2)", textTransform: "uppercase", letterSpacing: "0.1em", marginBottom: 6 }}>
                      Sponsored
                    </div>
                    <div style={{ fontSize: 16, color: "var(--ink)", marginBottom: 4, fontWeight: 500 }}>
                      Track side effects between doses
                    </div>
                    <div style={{ fontSize: 13, color: "var(--ink-2)", marginBottom: 8 }}>
                      Companion logging app for nausea, fatigue, and weight — syncs with this schedule.
                    </div>
                    <div style={{ fontSize: 12, color: "var(--accent-ink)", fontFamily: "var(--mono)" }}>
                      sponsor.example →
                    </div>
                  </div>
                )}

                <div className="section-h">
                  <h2 style={{ fontSize: 22 }}>Upcoming injections</h2>
                  <span className="meta">Next 12</span>
                </div>
                <window.DoseList events={computed.events} schedule={computed.schedule} limit={12} />
              </div>

              <aside className="rail">
                <window.ExportPanel
                  schedule={computed.schedule}
                  events={computed.events}
                  includeReminders={activePlan.includeReminders}
                  onChangeReminders={(r) => setActivePlan({ ...activePlan, includeReminders: r })}
                />
                {tweaks.showAffiliate && <window.AffiliatePanel />}
                {tweaks.showAds && <window.AdSlot size="300x250" label="300 × 250 medium rectangle" />}
              </aside>
            </div>
          </>
        )}

        {/* Daily log */}
        <window.DailyLog />

        {/* How it works */}
        <div className="section-h" id="how">
          <h2>How TitratePlan works</h2>
          <span className="meta">Three things only</span>
        </div>
        <div className="card card-pad" style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 32 }}>
          <div>
            <div className="label-mono" style={{ color: "var(--accent-ink)" }}>01 · Pick</div>
            <h3 style={{ fontFamily: "var(--serif)", fontSize: 20, fontWeight: 400, margin: "8px 0" }}>Your medication & plan</h3>
            <p className="small muted">Pick semaglutide or tirzepatide, and whether you're titrating for type 2 diabetes or chronic weight management. The standard prescribing-information schedule is loaded for you.</p>
          </div>
          <div>
            <div className="label-mono" style={{ color: "var(--accent-ink)" }}>02 · Plan</div>
            <h3 style={{ fontFamily: "var(--serif)", fontSize: 20, fontWeight: 400, margin: "8px 0" }}>Your start date & injection day</h3>
            <p className="small muted">Choose the day you'll inject each week. We project every dose forward, marking each escalation step so you can plan around possible side-effect days.</p>
          </div>
          <div>
            <div className="label-mono" style={{ color: "var(--accent-ink)" }}>03 · Export</div>
            <h3 style={{ fontFamily: "var(--serif)", fontSize: 20, fontWeight: 400, margin: "8px 0" }}>One file, all your calendars</h3>
            <p className="small muted">Download a single .ics file. Drop it into Apple Calendar, Google Calendar, Outlook — every dose appears as an all-day event with optional reminders.</p>
          </div>
        </div>

        {/* Educational + policy content (footer anchor targets) */}

        {/* FAQ-ish strip */}
        <div className="section-h" id="faq">
          <h2>Frequently asked</h2>
          <span className="meta">Educational</span>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
          {[
            ["Is this medical advice?", "No. TitratePlan is an educational scheduling tool. Always confirm any dose change with your prescriber. Side effects can require staying on a step longer than four weeks."],
            ["What if I miss a dose?", "If your scheduled dose is more than 5 days late, most prescribing information says to skip it and resume on the next scheduled day. Check with your clinician."],
            ["Does my data leave my browser?", "No accounts, no servers. Your schedule lives in your calendar app once you export. Nothing is uploaded."],
            ["What about compounded GLP-1s?", "Use the Custom plan flow (coming soon) or pick the closest schedule and edit your start date. Always follow your compounding pharmacy's titration guidance."],
          ].map(([q, a]) => (
            <div key={q} className="card card-pad">
              <h3 style={{ fontFamily: "var(--serif)", fontSize: 18, fontWeight: 400, marginBottom: 8 }}>{q}</h3>
              <p className="small" style={{ color: "var(--ink-2)" }}>{a}</p>
            </div>
          ))}
        </div>
      </div>
      )}

      <footer>
        <div className="footer-inner">
          <div>
            <div className="brand" style={{ marginBottom: 14 }}>
              <span className="brand-mark"></span>
              <span>TitratePlan</span>
            </div>
            <p className="footer-disclaimer">
              <strong>Important:</strong> TitratePlan is an independent educational tool. It is not affiliated with, endorsed by,
              or sponsored by Novo Nordisk, Eli Lilly, or any pharmaceutical manufacturer. Brand names referenced are the
              property of their respective owners and used here for informational purposes only. The schedules shown reflect
              standard prescribing information and may not match your prescriber's plan. <strong>Always follow your clinician's
              guidance.</strong> Not for medical use.
            </p>
          </div>
          <div className="footer-col">
            <h5>Tools</h5>
            <ul>
              <li><a href="#top">Schedule planner</a></li>
              <li><a href="#log">Daily log</a></li>
              <li><a href="#site-rotation">Site rotation guide</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h5>Learn</h5>
            <ul>
              <li><a href="#titration">How titration works</a></li>
              <li><a href="#missed-dose">Missed a dose?</a></li>
              <li><a href="#storage">Storage &amp; travel</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h5>Site</h5>
            <ul>
              <li><a href="#about">About</a></li>
              <li><a href="#privacy">Privacy</a></li>
              <li><a href="#advertising">Advertising disclosure</a></li>
            </ul>
          </div>
        </div>
      </footer>

      {/* Tweaks panel */}
      <window.TweaksPanel title="Tweaks">
        <window.TweakSection label="Theme">
          <window.TweakRadio
            label="Mode"
            value={tweaks.theme}
            onChange={(v) => setTweak("theme", v)}
            options={["light", "wellness", "dark"]}
          />
        </window.TweakSection>
        <window.TweakSection label="Layout">
          <window.TweakToggle
            label="Show ad slots"
            value={tweaks.showAds}
            onChange={(v) => setTweak("showAds", v)}
          />
          <window.TweakToggle
            label="Telehealth providers"
            value={tweaks.showAffiliate}
            onChange={(v) => setTweak("showAffiliate", v)}
          />
          <window.TweakToggle
            label="Site rotation widget"
            value={tweaks.showSiteRotation}
            onChange={(v) => setTweak("showSiteRotation", v)}
          />
        </window.TweakSection>
      </window.TweaksPanel>
    </>
  );
}

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