// Site sections — idea, the interactive practice loop, contact, footer.
// Deliberately abstract: no app names, no specific skills, no timelines, no external links.

// ───────── Section wrapper ─────────
function Section({ id, eyebrow, title, sub, children, sunken = false, dark = false, narrow = false }) {
  const bg = dark ? GB.ink : sunken ? GB.stone0 : GB.paper;
  const fg = dark ? '#fff' : GB.ink;
  return (
    <section id={id} style={{
      background: bg, color: fg,
      borderTop: sunken && !dark ? `1px solid ${GB.divider}` : 'none',
      borderBottom: sunken && !dark ? `1px solid ${GB.divider}` : 'none',
      padding: '96px 0', fontFamily: GB.font,
    }}>
      <div style={{ maxWidth: narrow ? 820 : 1120, margin: '0 auto', padding: '0 32px' }}>
        {(eyebrow || title) && (
          <div style={{ marginBottom: 56, maxWidth: 760 }}>
            {eyebrow && <div style={{
              fontSize: 12, fontWeight: 500, letterSpacing: '0.04em',
              color: dark ? 'rgba(255,255,255,0.55)' : GB.fg3, marginBottom: 16,
            }}>{eyebrow.toUpperCase()}</div>}
            {title && <h2 style={{
              margin: 0, fontSize: 'clamp(36px, 4.8vw, 56px)', fontWeight: 300,
              letterSpacing: '-0.035em', lineHeight: 1.05, color: fg,
            }}>{title}</h2>}
            {sub && <p style={{
              margin: '20px 0 0', maxWidth: 620, fontSize: 18, lineHeight: 1.55,
              color: dark ? 'rgba(255,255,255,0.65)' : GB.fg2,
            }}>{sub}</p>}
          </div>
        )}
        {children}
      </div>
    </section>
  );
}

// ───────── The idea ─────────
function Idea() {
  const items = [
    {
      n: '01',
      title: 'Small is the unit.',
      body: 'Sessions are short on purpose. Short enough that a tired day, a busy day, a Sunday — none of them are a reason to skip. That is how skill compounds.',
    },
    {
      n: '02',
      title: 'A number that goes up.',
      body: 'Every product has one honest metric. You watch it climb. Nothing fuzzy, nothing inflated — only what the practice actually moved.',
    },
    {
      n: '03',
      title: 'Calm, not loud.',
      body: 'No streak shaming, no push spam, no confetti. If you miss a day, the ring resets. Tomorrow you do it again.',
    },
    {
      n: '04',
      title: 'Skill, not vibes.',
      body: 'Each product teaches a specific, observable thing — something you can point at and say: I can do this now, and I couldn\u2019t before.',
    },
  ];
  return (
    <Section id="idea" eyebrow="The idea" title="Practice should feel like a kept promise — to yourself.">
      <div className="gbs-grid-2" style={{
        display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 32,
      }}>
        {items.map(it => (
          <div key={it.n} style={{
            padding: 32, borderRadius: 20, background: '#fff',
            border: `1px solid ${GB.border}`, fontFamily: GB.font,
          }}>
            <div style={{
              fontFamily: GB.mono, fontSize: 13, color: GB.fg3,
              fontWeight: 500, letterSpacing: '0.04em', marginBottom: 16,
            }}>{it.n}</div>
            <div style={{
              fontSize: 22, fontWeight: 500, letterSpacing: '-0.015em',
              lineHeight: 1.25, color: GB.ink,
            }}>{it.title}</div>
            <p style={{
              margin: '12px 0 0', fontSize: 15, lineHeight: 1.6, color: GB.fg2,
            }}>{it.body}</p>
          </div>
        ))}
      </div>
    </Section>
  );
}

// ───────── Interactive practice loop ─────────
// Abstract — one generic daily loop, no skill picker, no metric label tied to anything specific.

const STORAGE_KEY = 'gbs-demo-v2';
const DAY_MS = 24 * 60 * 60 * 1000;
const DAY_LABELS = ['M', 'T', 'W', 'T', 'F', 'S', 'S'];

function loadState() {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (raw) return JSON.parse(raw);
  } catch (e) {}
  return { days: [], total: 0 };
}
function saveState(s) {
  try { localStorage.setItem(STORAGE_KEY, JSON.stringify(s)); } catch (e) {}
}
function ymd(d = new Date()) {
  const y = d.getFullYear();
  const m = String(d.getMonth() + 1).padStart(2, '0');
  const da = String(d.getDate()).padStart(2, '0');
  return `${y}-${m}-${da}`;
}
function startOfWeek(d = new Date()) {
  const dd = new Date(d); dd.setHours(0,0,0,0);
  const diff = (dd.getDay() + 6) % 7; // Monday anchor
  dd.setDate(dd.getDate() - diff);
  return dd;
}

function PracticeLoop() {
  const [state, setState] = React.useState(() => loadState());
  const [pulseDay, setPulseDay] = React.useState(null);
  const today = ymd();

  React.useEffect(() => { saveState(state); }, [state]);

  const weekStart = startOfWeek();
  const week = Array.from({ length: 7 }).map((_, i) => {
    const d = new Date(weekStart.getTime() + i * DAY_MS);
    return { date: ymd(d), letter: DAY_LABELS[i], isToday: ymd(d) === today, isFuture: d.getTime() > Date.now() };
  });
  const doneSet = new Set(state.days);
  const weekDone = week.filter(w => doneSet.has(w.date)).length;
  const progress = weekDone / 7;
  const todayDone = doneSet.has(today);

  // Streak: count back from today through consecutive done days
  let streak = 0;
  for (let i = 0; i < 365; i++) {
    const d = new Date(Date.now() - i * DAY_MS);
    if (doneSet.has(ymd(d))) streak += 1;
    else if (i === 0) continue;
    else break;
  }

  const practice = () => {
    if (todayDone) return;
    setPulseDay(today);
    setTimeout(() => setPulseDay(null), 600);
    setState(s => ({
      days: Array.from(new Set([...s.days, today])).slice(-180),
      total: s.total + 1,
    }));
  };
  const reset = () => setState({ days: [], total: 0 });

  return (
    <Section
      id="try"
      eyebrow="Try the loop"
      title="The shape of a practice."
      sub="Tap once a day. The ring fills, the number climbs. This is the entire shape of how a Get Better product feels — quiet, daily, honest. Come back tomorrow and the day after."
      dark
    >
      <div className="gbs-grid-2" style={{
        display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 56, alignItems: 'center',
      }}>
        {/* Card */}
        <div style={{
          background: '#fff', color: GB.ink, borderRadius: 28, padding: 36,
          boxShadow: '0 30px 80px rgba(0,0,0,0.30), 0 2px 6px rgba(0,0,0,0.10)',
          fontFamily: GB.font, position: 'relative',
        }}>
          <div style={{
            display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8,
          }}>
            <div style={{ fontSize: 13, color: GB.fg3, letterSpacing: '0.02em' }}>
              Today
            </div>
            <div style={{
              fontFamily: GB.mono, fontSize: 11, padding: '4px 10px', borderRadius: 9999,
              background: GB.sproutSoft, color: GB.sproutDeep, fontWeight: 600, letterSpacing: '0.06em',
              whiteSpace: 'nowrap',
            }}>{streak} DAY{streak === 1 ? '' : 'S'}</div>
          </div>

          <div style={{ display: 'flex', justifyContent: 'center', padding: '20px 0' }}>
            <StreakRing
              progress={progress}
              size={200}
              label={`${weekDone} / 7`}
              sub="this week"
            />
          </div>

          {/* Day strip */}
          <div style={{
            display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 6, marginTop: 8,
          }}>
            {week.map(d => {
              const done = doneSet.has(d.date);
              const pulsing = pulseDay === d.date;
              return (
                <div key={d.date} style={{
                  display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8,
                }}>
                  <div style={{
                    fontSize: 11, color: d.isToday ? GB.ink : GB.fg3,
                    fontWeight: d.isToday ? 600 : 500, letterSpacing: '0.04em',
                  }}>{d.letter}</div>
                  <div style={{
                    width: 30, height: 30, borderRadius: 9999,
                    background: done ? GB.sprout : 'transparent',
                    border: done ? 'none' : `1.5px solid ${d.isToday ? GB.ink : GB.stone1}`,
                    display: 'grid', placeItems: 'center',
                    transition: `all 220ms ${GB.ease}`,
                    transform: pulsing ? 'scale(1.18)' : 'scale(1)',
                    opacity: d.isFuture ? 0.4 : 1,
                  }}>
                    {done && (
                      <svg width="12" height="12" viewBox="0 0 12 12" fill="none">
                        <path d="M2.5 6.2l2.2 2.2L9.5 3.5" stroke="#fff" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round"/>
                      </svg>
                    )}
                  </div>
                </div>
              );
            })}
          </div>

          {/* Total */}
          <div style={{
            marginTop: 24, padding: '16px 18px', borderRadius: 14, background: GB.stone0,
            display: 'flex', alignItems: 'baseline', justifyContent: 'space-between',
          }}>
            <div>
              <div style={{ fontSize: 12, color: GB.fg3, letterSpacing: '0.02em' }}>days practiced</div>
              <div style={{
                fontFamily: GB.mono, fontSize: 32, fontWeight: 600, letterSpacing: '-0.02em',
                marginTop: 2, fontVariantNumeric: 'tabular-nums',
              }}>{state.total}</div>
            </div>
            <div style={{ fontSize: 13, color: GB.fg3 }}>total</div>
          </div>

          {/* CTA */}
          <button onClick={practice} disabled={todayDone} style={{
            marginTop: 20, width: '100%', padding: '16px 22px',
            border: 'none', borderRadius: 14, cursor: todayDone ? 'default' : 'pointer',
            background: todayDone ? GB.stone0 : GB.sprout,
            color: todayDone ? GB.fg2 : '#fff',
            fontFamily: GB.font, fontSize: 16, fontWeight: 600, letterSpacing: '-0.01em',
            transition: `background 220ms ${GB.ease}, opacity 120ms ${GB.ease}`,
          }}
          onMouseDown={e => e.currentTarget.style.opacity = '0.7'}
          onMouseUp={e => e.currentTarget.style.opacity = '1'}
          onMouseLeave={e => e.currentTarget.style.opacity = '1'}>
            {todayDone ? 'Done for today' : 'Mark today done'}
          </button>
        </div>

        {/* Side: copy + stats + reset */}
        <div>
          <p style={{
            margin: 0, fontSize: 22, lineHeight: 1.5, color: 'rgba(255,255,255,0.92)',
            maxWidth: 460, fontWeight: 400, letterSpacing: '-0.015em',
          }}>
            One tap a day. Nothing more is asked of you.
          </p>
          <p style={{
            margin: '20px 0 0', fontSize: 16, lineHeight: 1.6, color: 'rgba(255,255,255,0.65)',
            maxWidth: 460,
          }}>
            Come back tomorrow and the day after. The ring fills, the count climbs. You will feel the difference between <em style={{ fontStyle: 'normal', color: '#fff' }}>I am trying</em> and <em style={{ fontStyle: 'normal', color: '#fff' }}>I have shown up 12 days in a row</em>.
          </p>

          <div style={{
            marginTop: 32, display: 'flex', gap: 12, alignItems: 'center', flexWrap: 'wrap',
          }}>
            <Stat label="current streak" value={`${streak} day${streak === 1 ? '' : 's'}`}/>
            <Stat label="days total" value={`${state.total}`}/>
            <button onClick={reset} style={{
              marginLeft: 'auto', padding: '10px 14px', borderRadius: 10,
              background: 'transparent', color: 'rgba(255,255,255,0.6)',
              border: '1px solid rgba(255,255,255,0.18)',
              fontFamily: GB.font, fontSize: 13, fontWeight: 500, cursor: 'pointer',
            }}>Reset</button>
          </div>

          <div style={{
            marginTop: 28, fontSize: 12, color: 'rgba(255,255,255,0.4)',
          }}>
            Saved locally in your browser. Nothing sent anywhere.
          </div>
        </div>
      </div>
    </Section>
  );
}

function Stat({ label, value }) {
  return (
    <div style={{
      padding: '12px 16px', borderRadius: 12,
      background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.10)',
      minWidth: 110,
    }}>
      <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.55)', letterSpacing: '0.04em' }}>{label.toUpperCase()}</div>
      <div style={{
        fontFamily: GB.mono, fontSize: 18, fontWeight: 600, color: '#fff', marginTop: 4,
        fontVariantNumeric: 'tabular-nums', letterSpacing: '-0.01em',
      }}>{value}</div>
    </div>
  );
}

// ───────── Contact ─────────
function Contact() {
  const [copied, setCopied] = React.useState(false);
  const email = 'info@getbettersoftware.com';
  const copy = async () => {
    try { await navigator.clipboard.writeText(email); setCopied(true); setTimeout(() => setCopied(false), 1600); }
    catch (e) { setCopied(false); }
  };
  return (
    <Section id="contact" sunken>
      <div style={{ maxWidth: 720 }}>
        <div style={{
          fontSize: 12, fontWeight: 500, letterSpacing: '0.04em',
          color: GB.fg3, marginBottom: 16,
        }}>SAY HELLO</div>
        <h2 style={{
          margin: 0, fontSize: 'clamp(36px, 4.8vw, 56px)', fontWeight: 300,
          letterSpacing: '-0.035em', lineHeight: 1.05, color: GB.ink, maxWidth: 540,
        }}>
          One inbox, one person, one reply.
        </h2>
        <p style={{
          margin: '20px 0 0', maxWidth: 540, fontSize: 18, lineHeight: 1.55, color: GB.fg2,
        }}>
          Tell me what you would like to get better at. Whatever it is — feedback, a question, just hi — it lands in the same place, and it gets read.
        </p>

        <div style={{
          marginTop: 36, display: 'flex', alignItems: 'center', gap: 12,
          padding: '14px 18px', background: '#fff', border: `1px solid ${GB.border}`,
          borderRadius: 14, maxWidth: 520,
        }}>
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
            <rect x="3" y="5" width="18" height="14" rx="2" stroke="#0E1411" strokeWidth="1.75"/>
            <path d="M3 7l9 6 9-6" stroke="#0E1411" strokeWidth="1.75" strokeLinecap="round"/>
          </svg>
          <a href={`mailto:${email}`} style={{
            flex: 1, color: GB.ink, textDecoration: 'none',
            fontSize: 16, fontFamily: GB.mono, fontWeight: 500,
            overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
          }}>{email}</a>
          <button onClick={copy} style={{
            padding: '8px 12px', borderRadius: 10, border: 'none', cursor: 'pointer',
            background: copied ? GB.sprout : GB.ink, color: '#fff',
            fontFamily: GB.font, fontSize: 13, fontWeight: 500,
            transition: `background 220ms ${GB.ease}`,
          }}>{copied ? 'Copied' : 'Copy'}</button>
        </div>

        <div style={{ marginTop: 16, fontSize: 13, color: GB.fg3 }}>
          Replies are slow but real.
        </div>
      </div>
    </Section>
  );
}

// ───────── Footer ─────────
function Footer() {
  return (
    <footer style={{
      borderTop: `1px solid ${GB.divider}`, padding: '32px 32px',
      fontFamily: GB.font, background: GB.paper,
    }}>
      <div style={{
        maxWidth: 1120, margin: '0 auto',
        display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 16,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <img src="assets/logo-mark.svg" alt="" style={{ height: 22 }}/>
          <span style={{ fontSize: 13, color: GB.fg3 }}>
            © 2026 Get Better Software · Made in one place, slowly.
          </span>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, {
  Section, Idea, PracticeLoop, Contact, Footer,
});
