// tracker.jsx — PAGE 2: The Tracker (habit grid + claim)
const { useRef: useRefT, useEffect: useEffectT, useState: useStateT } = React;

const TOTAL = 70;

/* Reward unlocks in stages as the habit builds. Milestones mirror Page 1's arc:
   day 21 (habit locked), day 45 (past the hard part), day 70 (finished). */
const REWARD_MS = [
{ day: 21, amt: 10, title: "Habit locked", flag: "3 weeks in" },
{ day: 45, amt: 15, title: "Past the hard part", flag: "6 weeks in" },
{ day: 70, amt: 25, title: "Hyro 70", flag: "Finish" }];

const MS_DAYS = { 21: "Habit locked", 45: "Past the hard part", 70: "Hyro 70" };
const REWARD_TOTAL = 50;

function unlockedBy(day) {
  return REWARD_MS.reduce((sum, m) => day >= m.day ? sum + m.amt : sum, 0);
}

function currentStreak(checkedSet, day) {
  // consecutive checked days ending at the most recent checked day up to `day`
  let streak = 0;
  for (let d = day; d >= 1; d--) {
    if (checkedSet.has(d)) streak++;else
    if (d === day) continue; // today not yet checked doesn't break a prior streak
    else break;
  }
  return streak;
}

function Box({ day, state, tappable, justChecked, onTap }) {
  return (
    <div
      className={"bottle-cell " + state + (tappable ? " tappable" : "") + (justChecked ? " just-checked" : "")}
      onClick={tappable ? () => onTap(day) : undefined}
      role={tappable ? "button" : undefined}
      aria-label={`Day ${day}${state === "done" ? ", done" : ""}`}>
      
      <Bottle state={state} />
      <span className="bottle-day">{day}</span>
    </div>);

}

function MsBanner({ ms, currentDay }) {
  const reached = currentDay >= ms.day;
  const unlocked = unlockedBy(currentDay);
  return (
    <div className={"ms-banner" + (reached ? " reached" : "")}>
      <span className="ms-banner-amt">+${ms.amt}</span>
      <div>
        <span className="bdg">{reached ? `Unlocked · Day ${ms.day}` : `Day ${ms.day} · ${ms.flag}`}</span>
        <h4>{ms.title}</h4>
      </div>
    </div>);

}

function ClaimCard({ currentDay, claimed, onClaim, onRetake, member }) {
  const unlocked = currentDay >= TOTAL;
  const toGo = TOTAL - currentDay;
  const banked = unlockedBy(currentDay);
  const [open, setOpen] = useStateT(false);
  const [name, setName] = useStateT(member.firstName || "");
  const [email, setEmail] = useStateT(member.email || "");
  const [err, setErr] = useStateT("");

  function submitClaim(e) {
    e.preventDefault();
    if (!name.trim()) {setErr("Add your name");return;}
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email.trim())) {setErr("That email does not look right");return;}
    setErr("");onClaim();
  }

  return (
    <div className={"claim-card" + (unlocked ? " unlocked" : "")}>
      <span className="bdg" style={{ fontFamily: "var(--font-display)", textTransform: "uppercase", fontSize: 12, letterSpacing: "0.05em", opacity: 0.85 }}>The reward</span>
      <div className="amt lemon">${banked}<span className="amt-of">/ $50</span></div>
      <h4>{claimed ? "Claim submitted" : unlocked ? "Claim your $50" : "Unlocking as you go"}</h4>

      {/* staged breakdown */}
      <ul className="claim-stages">
        {REWARD_MS.map((m) => {
          const done = currentDay >= m.day;
          return (
            <li key={m.day} className={done ? "done" : ""}>
              <span className="cs-ic">{done ? Icon.check({ style: { width: 13, height: 13, stroke: "currentColor", fill: "none" } }) : Icon.lock({ style: { width: 12, height: 12, stroke: "currentColor", fill: "none" } })}</span>
              <span className="cs-day">Day {m.day}</span>
              <span className="cs-amt">+${m.amt}</span>
            </li>);

        })}
      </ul>

      {claimed ?
      <p>Awesome work! We've just dropped $50 Hyro credit into your account. Happy hydrating!
</p> : unlocked ?
      <p>Wow! You finished the 70-day challenge!
Confirm your details to claim your reward.
      </p> : <p>${banked} unlocked so far. Keep your daily Hyro going and the rest banks at each milestone. Claim the lot at Day 70.</p>
      }

      {claimed ?
      <>
        <span className="claim-lockrow">{Icon.check({ style: { width: 14, height: 14, stroke: "currentColor", fill: "none" } })} Reward claimed</span>
        <button type="button" className="claim-retake" onClick={onRetake}>{Icon.refresh({ style: { width: 15, height: 15, stroke: "currentColor", fill: "none" } })} Re-take the 70-Day Challenge</button>
      </> :
      unlocked ?
      open ?
      <form className="claim-form" onSubmit={submitClaim}>
            <input className="claim-input" value={name} onChange={(e) => setName(e.target.value)} placeholder="Your name" autoComplete="name" />
            <input className="claim-input" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="you@email.com" type="email" autoComplete="email" />
            {err && <div className="claim-err">{err}</div>}
            <button type="submit" className="cta on-red block">Submit my claim</button>
            <button type="button" className="claim-cancel" onClick={() => setOpen(false)}>Cancel</button>
          </form> :

      <button className="cta on-red block" onClick={() => setOpen(true)}>Claim my $50</button> :


      <span className="claim-lockrow">{Icon.lock({ style: { width: 14, height: 14, stroke: "currentColor", fill: "none" } })} Full claim at Day 70 &middot; {toGo} to go</span>
      }
    </div>);

}

function Tracker({ member, currentDay, checked, onToggle, claimed, onClaim, onRetake, justChecked }) {
  const checkedSet = new Set(checked);
  const checkedCount = checked.length;
  const todayWeekRef = useRefT(null);
  const streak = currentStreak(checkedSet, currentDay);
  const toGo = Math.max(0, TOTAL - currentDay);
  const dayProgress = Math.min(100, currentDay / TOTAL * 100);
  const todayChecked = checkedSet.has(currentDay);
  const banked = unlockedBy(currentDay);

  // auto-centre today's week (no scrollIntoView)
  useEffectT(() => {
    const el = todayWeekRef.current;
    if (!el) return;
    const id = setTimeout(() => {
      const r = el.getBoundingClientRect();
      const target = window.scrollY + r.top - Math.max(150, window.innerHeight * 0.32);
      window.scrollTo({ top: Math.max(0, target), behavior: "smooth" });
    }, 350);
    return () => clearTimeout(id);
  }, [currentDay]);

  function stateFor(day) {
    if (checkedSet.has(day)) return "done";
    if (day === currentDay) return "today";
    if (day < currentDay) return "missable";
    return "future";
  }
  function tappableFor(day) {
    return day <= currentDay; // today + recoverable past days
  }

  const weeks = Array.from({ length: 10 }, (_, w) =>
  Array.from({ length: 7 }, (_, d) => w * 7 + d + 1)
  );
  const todayWeekIdx = Math.floor((currentDay - 1) / 7);

  function jumpToday() {
    const el = todayWeekRef.current;
    if (!el) return;
    const r = el.getBoundingClientRect();
    window.scrollTo({ top: Math.max(0, window.scrollY + r.top - 150), behavior: "smooth" });
  }

  return (
    <div className="tracker-page" data-screen-label="Tracker">
      {/* TOP */}
      <div className="tk-top">
        <div className="wrap">
          <div className="tk-lockup">
            <img src="assets/logos/hyro-wordmark-white.png" alt="Hyro" />
          </div>
          <h1 className="tk-greeting">Welcome to your tracker, <em>{member.firstName || "legend"}</em></h1>
          <div className="tk-stat-row">
            <span className="tk-daycount">Day {currentDay} of 70</span>
            <span className="tk-streak"><span className="streak-emoji" aria-hidden="true">🔥</span> {streak} day streak</span>
          </div>
          <div className="tk-progress"><div style={{ width: dayProgress + "%" }}></div></div>
          <p className="tk-countdown"><b>${banked}</b> of $50 banked &middot; {toGo} {toGo === 1 ? "day" : "days"} to go &middot; {checkedCount}/70 days hydrated</p>
        </div>
      </div>

      {/* BODY */}
      <div className="wrap tk-body">
        <div className="tk-layout">
          <div className="tk-grid-col">
            {weeks.map((days, w) => {
              const isTodayWeek = w === todayWeekIdx;
              const row =
              <div className="wk" key={"wk" + w} ref={isTodayWeek ? todayWeekRef : null}>
                  <div className="wk-head">
                    <span className="wk-lbl">Week {w + 1}{isTodayWeek ? " · you are here" : ""}</span>
                  </div>
                  <div className="wk-row">
                    {days.map((day) =>
                  <Box key={day} day={day} state={stateFor(day)}
                  tappable={tappableFor(day)} justChecked={justChecked === day}
                  onTap={onToggle} />
                  )}
                  </div>
                </div>;

              // reward milestone banners after the week containing day 21 and day 45
              if (w === 2) return [row, <MsBanner key="ms21" ms={REWARD_MS[0]} currentDay={currentDay} />];
              if (w === 6) return [row, <MsBanner key="ms45" ms={REWARD_MS[1]} currentDay={currentDay} />];
              return row;
            })}
            {/* claim card inline on mobile, right rail on desktop handled by order */}
            <div className="hide-desktop" style={{ marginTop: 8 }}>
              <ClaimCard currentDay={currentDay} claimed={claimed} onClaim={onClaim} onRetake={onRetake} member={member} />
            </div>
          </div>

          {/* right rail (desktop) */}
          <div className="hide-mobile">
            <ClaimCard currentDay={currentDay} claimed={claimed} onClaim={onClaim} onRetake={onRetake} member={member} />
          </div>
        </div>
      </div>

      {/* sticky check today (mobile) */}
      <div className="check-bar">
        <div className="info">
          {todayChecked ?
          <><b>Day {currentDay} done.</b> See you tomorrow.</> :
          <>Drank your Hyro? <b>Tick Day {currentDay}.</b></>}
        </div>
        {todayChecked ?
        <button className="cta" style={{ background: "var(--hyro-ink)", borderColor: "var(--hyro-ink)" }} onClick={jumpToday}>Day {currentDay} ✓</button> :
        <button className="cta" onClick={() => onToggle(currentDay)}>Check today</button>}
      </div>
    </div>);

}

window.Tracker = Tracker;