// Getfiit DS Landing — nav + hero
// Reads theme + copy + visibility from window.GfCtx (React Context).

const GfCtx = React.createContext(null);
window.GfCtx = GfCtx;
const useGf = () => React.useContext(GfCtx);

// ─────────── NAV ───────────
function GfNav({ waLink }) {
  const { t, copy, bp } = useGf();
  const { isMobile } = bp;
  return (
    <nav style={{
      position: 'sticky', top: 0, zIndex: 50,
      background: t.dark ? 'rgba(0,0,0,0.78)' : 'rgba(250,249,247,0.82)',
      backdropFilter: 'blur(16px)',
      borderBottom: `1px solid ${t.line}`,
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      padding: isMobile ? '14px 20px' : '18px 48px', fontFamily: 'Inter',
    }}>
      <a href="#top" style={{
        display: 'inline-flex', alignItems: 'center', gap: 10,
        color: t.text, textDecoration: 'none',
      }}>
        <svg width="22" height="22" viewBox="0 0 64 64">
          <rect width="64" height="64" rx="16" fill={t.dark ? '#0E0E0E' : '#0A0A0A'}/>
          <circle cx="32" cy="32" r="9" fill={t.accent}/>
        </svg>
        <span style={{ fontSize: 17, fontWeight: 600, letterSpacing: '-0.02em' }}>getfiit</span>
      </a>
      {!isMobile && (
        <div style={{ display: 'flex', gap: 36, fontSize: 13, color: t.muted }}>
          <a href="#how" style={{ color: 'inherit', textDecoration: 'none' }}>How</a>
          <a href="#log" style={{ color: 'inherit', textDecoration: 'none' }}>Logging</a>
          <a href="#proof" style={{ color: 'inherit', textDecoration: 'none' }}>Stories</a>
          <a href="#faq" style={{ color: 'inherit', textDecoration: 'none' }}>FAQ</a>
        </div>
      )}
      <a href={waLink} style={{
        display: 'inline-flex', alignItems: 'center', gap: 8,
        background: t.accent, color: t.onAccent,
        padding: isMobile ? '8px 12px' : '10px 16px', borderRadius: 999,
        fontWeight: 700, fontSize: 13, textDecoration: 'none',
        fontFamily: 'Inter',
      }}>
        <WhatsappGlyph size={14} ink={t.onAccent}/>
        {isMobile ? 'Start' : copy.navCta}
      </a>
    </nav>
  );
}

function WhatsappGlyph({ size = 16, ink = '#0A1100' }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill={ink}>
      <path d="M17.4 14.4c-.3-.1-1.7-.8-2-.9-.3-.1-.5-.1-.7.1-.2.3-.8.9-1 1.1-.2.2-.3.2-.6.1-.3-.1-1.2-.4-2.4-1.5-.9-.8-1.5-1.8-1.7-2.1-.2-.3 0-.5.1-.6.1-.1.3-.4.5-.6.1-.2.2-.3.3-.5.1-.2 0-.4 0-.5 0-.1-.7-1.6-.9-2.2-.2-.6-.5-.5-.7-.5h-.6c-.2 0-.5.1-.8.4-.3.3-1 1-1 2.5s1.1 2.9 1.2 3.1c.1.2 2.1 3.3 5.2 4.6 2.5 1.1 3.1 1 3.6 1 .6-.1 1.7-.7 2-1.4.2-.7.2-1.2.2-1.4-.1-.2-.3-.3-.6-.4zM12 2C6.5 2 2 6.5 2 12c0 1.9.5 3.6 1.4 5.2L2 22l4.9-1.3c1.5.8 3.3 1.3 5.1 1.3 5.5 0 10-4.5 10-10S17.5 2 12 2z"/>
    </svg>
  );
}

// ─────────── HERO ───────────
// Layouts: 'split' (panel right), 'stacked' (panel below), 'centered' (text only, no panel)
const CYCLING_WORDS = ['meal', 'weight', 'workout'];

function GfHero({ waLink }) {
  const { t, copy, tweaks, bp } = useGf();
  const { isMobile, isTablet } = bp;
  const layout = tweaks.heroLayout;

  const [wordIdx, setWordIdx] = React.useState(0);
  const [visible, setVisible] = React.useState(true);

  React.useEffect(() => {
    const id = setInterval(() => {
      setVisible(false);
      setTimeout(() => {
        setWordIdx(i => (i + 1) % CYCLING_WORDS.length);
        setVisible(true);
      }, 300);
    }, 5000);
    return () => clearInterval(id);
  }, []);

  const [titleA, titleB, titleC] = splitTitle(copy.heroTitle, copy.heroAccent);

  const cycleMatch = titleA.match(/^(.*?)(meal|weight|workout)(.*)$/i);

  const heroPadding = isMobile
    ? '40px 20px 48px'
    : isTablet
    ? '60px 32px 48px'
    : '80px 48px 64px';

  const titleEl = (
    <h1 style={{
      fontFamily: "'Bricolage Grotesque', Inter, sans-serif",
      fontWeight: 800,
      fontSize: layout === 'centered' ? 'clamp(40px, 11vw, 180px)' : 'clamp(40px, 9vw, 144px)',
      lineHeight: 0.9, letterSpacing: '-0.035em',
      color: t.text, margin: 0,
      textAlign: layout === 'centered' ? 'center' : 'left',
    }}>
      {cycleMatch ? (
        <>
          {cycleMatch[1].trim()}<br/>
          <span style={{
            display: 'inline-block',
            transition: 'opacity 0.3s ease, transform 0.3s ease',
            opacity: visible ? 1 : 0,
            transform: visible ? 'translateY(0)' : 'translateY(-6px)',
          }}>{CYCLING_WORDS[wordIdx]}</span>
          {cycleMatch[3]}
        </>
      ) : <>{titleA}</>}
      <br/>
      {titleB}{titleC && ' '}
      <span style={{ color: t.accent }}>{titleC}</span>
    </h1>
  );

  const subEl = (
    <p style={{
      fontFamily: 'Inter', fontSize: isMobile ? 17 : 20, lineHeight: 1.45,
      color: t.muted, maxWidth: layout === 'centered' ? 640 : 520,
      marginTop: 28,
      marginLeft: layout === 'centered' ? 'auto' : 0,
      marginRight: layout === 'centered' ? 'auto' : 0,
      textAlign: layout === 'centered' ? 'center' : 'left',
    }}>
      {copy.heroSub}
    </p>
  );

  const ctasEl = (
    <div style={{
      marginTop: 40, display: 'flex', alignItems: 'center', gap: 16, flexWrap: 'wrap',
      justifyContent: layout === 'centered' ? 'center' : 'flex-start',
    }}>
      <a href={waLink} style={{
        display: 'inline-flex', alignItems: 'center', gap: 10,
        background: t.accent, color: t.onAccent,
        padding: isMobile ? '15px 22px' : '18px 26px', borderRadius: 999,
        fontFamily: 'Inter', fontWeight: 700, fontSize: isMobile ? 15 : 16,
        textDecoration: 'none',
      }}>
        <WhatsappGlyph size={18} ink={t.onAccent}/>
        {copy.heroCta}
      </a>
      <a href="#how" style={{
        display: 'inline-flex', alignItems: 'center', gap: 8,
        color: t.text, fontFamily: 'Inter', fontWeight: 500, fontSize: 15,
        textDecoration: 'none', padding: '15px 4px',
      }}>
        See how it works
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"><path d="M5 12h14M13 5l7 7-7 7"/></svg>
      </a>
    </div>
  );

  const qrEl = (
    <div style={{
      marginTop: 28,
      display: 'flex', alignItems: 'center', gap: 14,
      justifyContent: layout === 'centered' ? 'center' : 'flex-start',
    }}>
      <div style={{
        background: '#F5F5F5', borderRadius: 10, padding: 6,
        display: 'inline-flex', flexShrink: 0,
      }}>
        <window.GF.RealQrCode size={72}/>
      </div>
      <div style={{ textAlign: 'left' }}>
        <div style={{
          fontFamily: 'Inter', fontSize: 10, fontWeight: 600,
          letterSpacing: '0.12em', textTransform: 'uppercase', color: t.muted,
        }}>SCAN TO START</div>
        <div style={{
          fontFamily: 'Inter', fontSize: 13, fontWeight: 500,
          color: t.text, marginTop: 3,
        }}>Open WhatsApp on your phone</div>
      </div>
    </div>
  );

  const statsEl = (
    <div style={{
      marginTop: isMobile ? 40 : 56, paddingTop: 28,
      borderTop: `1px solid ${t.line}`,
      display: 'grid',
      gridTemplateColumns: 'repeat(3, 1fr)',
      gap: 16,
      maxWidth: layout === 'centered' ? 720 : 'none',
      marginLeft: layout === 'centered' ? 'auto' : 0,
      marginRight: layout === 'centered' ? 'auto' : 0,
    }}>
      <HeroStat value="5s" label="TO LOG A MEAL" />
      <HeroStat value="Instant" label="COACH FEEDBACK" />
      <HeroStat value="Free" label="TO GET STARTED" />
    </div>
  );

  // Layout assembly
  if (layout === 'centered') {
    return (
      <section id="top" style={{ padding: heroPadding, maxWidth: 1100, margin: '0 auto', textAlign: 'center' }}>
        <div style={{ display: 'flex', justifyContent: 'center' }}>
          <window.GF.StatusLabel>GETFIIT · LIVE COACH</window.GF.StatusLabel>
        </div>
        <div style={{ marginTop: 28 }}>{titleEl}</div>
        {subEl}
        {ctasEl}
        {!isMobile && qrEl}
        {statsEl}
      </section>
    );
  }

  if (layout === 'stacked') {
    return (
      <section id="top" style={{ padding: heroPadding, maxWidth: 1320, margin: '0 auto' }}>
        <window.GF.StatusLabel>GETFIIT · LIVE COACH</window.GF.StatusLabel>
        <div style={{ marginTop: 28 }}>
          {titleEl}
          {subEl}
          {ctasEl}
          {!isMobile && qrEl}
        </div>
        <div style={{ marginTop: 64, display: 'grid', gridTemplateColumns: isMobile || isTablet ? '1fr' : 'minmax(0,1fr) 460px', gap: 64, alignItems: 'flex-start' }}>
          <div>{statsEl}</div>
          {!isMobile && <div><HeroChatPanel/></div>}
        </div>
      </section>
    );
  }

  // split — mobile: stacked text only; tablet: stacked text + chat panel below; desktop: side-by-side
  if (isMobile) {
    return (
      <section id="top" style={{ padding: heroPadding, maxWidth: 1320, margin: '0 auto' }}>
        <window.GF.StatusLabel>GETFIIT · LIVE COACH</window.GF.StatusLabel>
        <div style={{ marginTop: 28 }}>
          {titleEl}
          {subEl}
          {ctasEl}
          {statsEl}
        </div>
      </section>
    );
  }

  if (isTablet) {
    return (
      <section id="top" style={{ padding: heroPadding, maxWidth: 1320, margin: '0 auto' }}>
        <window.GF.StatusLabel>GETFIIT · LIVE COACH</window.GF.StatusLabel>
        <div style={{ marginTop: 28 }}>
          {titleEl}
          {subEl}
          {ctasEl}
          {qrEl}
          {statsEl}
        </div>
        <div style={{ marginTop: 48 }}>
          <HeroChatPanel/>
        </div>
      </section>
    );
  }

  return (
    <section id="top" style={{ padding: heroPadding, maxWidth: 1320, margin: '0 auto' }}>
      <window.GF.StatusLabel>GETFIIT · LIVE COACH</window.GF.StatusLabel>
      <div style={{
        marginTop: 28,
        display: 'grid', gridTemplateColumns: 'minmax(0,1fr) 460px',
        gap: 64, alignItems: 'flex-start',
      }}>
        <div>
          {titleEl}
          {subEl}
          {ctasEl}
          {qrEl}
          {statsEl}
        </div>
        <div style={{ position: 'relative' }}>
          <HeroChatPanel/>
        </div>
      </div>
    </section>
  );
}

// Splits "Log a meal\nin 5 seconds." into [lineA, lineB, accent]
// where accent is the trailing user-supplied phrase.
function splitTitle(full, accent) {
  if (!full) return ['', '', accent || ''];
  let main = full;
  if (accent) {
    const lc = full.toLowerCase();
    const ai = lc.lastIndexOf(accent.toLowerCase());
    if (ai >= 0) main = full.slice(0, ai).trim();
  }
  const parts = main.split('\n').map(s => s.trim()).filter(Boolean);
  if (parts.length >= 2) return [parts[0], parts.slice(1).join(' '), accent || ''];
  const words = main.split(/\s+/);
  if (words.length > 3) {
    const half = Math.ceil(words.length / 2);
    return [words.slice(0, half).join(' '), words.slice(half).join(' '), accent || ''];
  }
  return ['', main, accent || ''];
}

function HeroStat({ value, label }) {
  const { t, bp } = useGf();
  const { isMobile } = bp;
  return (
    <div>
      <div style={{
        fontFamily: "'Bricolage Grotesque', Inter, sans-serif",
        fontWeight: 800, fontSize: isMobile ? 32 : 44, lineHeight: 1, letterSpacing: '-0.02em',
        color: t.text, fontVariantNumeric: 'tabular-nums',
      }}>{value}</div>
      <div style={{
        marginTop: 8,
        fontFamily: 'Inter', fontWeight: 600, fontSize: 11,
        letterSpacing: '0.12em', textTransform: 'uppercase', color: t.muted,
      }}>{label}</div>
    </div>
  );
}

function HeroChatPanel() {
  const { t } = useGf();
  return (
    <div style={{
      background: t.surface, borderRadius: 20,
      boxShadow: `inset 0 0 0 1px ${t.surfaceLine}`,
      padding: 20, position: 'relative', overflow: 'hidden',
    }}>
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        paddingBottom: 16, borderBottom: `1px solid ${t.line}`,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <div style={{
            width: 32, height: 32, borderRadius: '50%',
            background: t.accent, color: t.onAccent,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontWeight: 800, fontSize: 14, fontFamily: 'Bricolage Grotesque',
          }}>g</div>
          <div>
            <div style={{ fontFamily: 'Inter', fontWeight: 600, fontSize: 13, color: t.text }}>
              Getfiit Coach
            </div>
            <div style={{ fontFamily: 'Inter', fontSize: 11, color: t.muted, display: 'flex', alignItems: 'center', gap: 5 }}>
              <span style={{ width: 6, height: 6, borderRadius: '50%', background: t.accent }} />
              typing…
            </div>
          </div>
        </div>
        <div style={{
          fontFamily: 'Inter', fontSize: 10, fontWeight: 600,
          color: t.muted, letterSpacing: '0.12em', textTransform: 'uppercase',
        }}>via WhatsApp</div>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 10, padding: '20px 0 4px' }}>
        <UserBubble>
          <div style={{
            width: '100%', aspectRatio: '4/3', borderRadius: 8, overflow: 'hidden',
            background: t.dark
              ? 'repeating-linear-gradient(135deg, #181818 0 1px, transparent 1px 14px), #050505'
              : 'repeating-linear-gradient(135deg, #E5E2DA 0 1px, transparent 1px 14px), #EFEAE0',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: t.dim, fontSize: 10, letterSpacing: '0.3em',
            fontFamily: 'Inter', fontWeight: 500, marginBottom: 6,
          }}>[ MEAL PHOTO ]</div>
          <div style={{ fontSize: 14, color: t.text, fontFamily: 'Inter' }}>lunch 🥗</div>
          <BubbleMeta time="12:42" sent />
        </UserBubble>

        <CoachBubble>
          <div style={{ fontFamily: 'Inter', fontSize: 14, color: t.text }}>
            Logged: <strong>Greek salad + grilled chicken</strong>
          </div>
          <div style={{
            marginTop: 10,
            display: 'flex', justifyContent: 'space-between', alignItems: 'center',
            padding: '10px 12px',
            background: t.dark ? '#000' : '#FAF7EF',
            border: t.dark ? 'none' : `1px solid ${t.line}`,
            borderRadius: 10,
          }}>
            <MiniRing value="480" suffix="kcal" color="#9DEE2A" pct={62} />
            <MiniRing value="38" suffix="g·P" color="#F8A4A0" pct={70} />
            <MiniRing value="24" suffix="g·C" color="#F08A2A" pct={28} />
            <MiniRing value="22" suffix="g·F" color="#F4B72E" pct={45} />
          </div>
          <div style={{ marginTop: 8, fontFamily: 'Inter', fontSize: 13, color: t.muted }}>
            Solid choice. You're at 62% of today's protein — aim for fish or eggs at dinner.
          </div>
          <BubbleMeta time="12:42" />
        </CoachBubble>

        <UserBubble compact>
          <div style={{ fontSize: 14, color: t.text, fontFamily: 'Inter' }}>ok 👍</div>
          <BubbleMeta time="12:43" sent />
        </UserBubble>
      </div>
    </div>
  );
}

function UserBubble({ children, compact }) {
  const { t } = useGf();
  return (
    <div style={{
      alignSelf: 'flex-end', maxWidth: '88%',
      background: t.dark ? 'rgba(198, 255, 61, 0.10)' : 'rgba(99, 168, 0, 0.12)',
      border: t.dark ? '1px solid rgba(198, 255, 61, 0.18)' : '1px solid rgba(99, 168, 0, 0.22)',
      borderRadius: 14, padding: compact ? '8px 12px' : '10px 12px',
      display: 'flex', flexDirection: 'column',
      marginLeft: 'auto',
    }}>
      {children}
    </div>
  );
}

function CoachBubble({ children }) {
  const { t } = useGf();
  return (
    <div style={{
      alignSelf: 'flex-start', maxWidth: '92%',
      background: t.dark ? '#161616' : '#FFFFFF',
      border: `1px solid ${t.line}`,
      borderRadius: 14, padding: '12px 14px',
    }}>
      {children}
    </div>
  );
}

function BubbleMeta({ time, sent }) {
  const { t } = useGf();
  return (
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'flex-end', gap: 4,
      marginTop: 4, fontFamily: 'Inter', fontSize: 10, color: t.muted,
    }}>
      <span>{time}</span>
      {sent && (
        <svg width="14" height="10" viewBox="0 0 16 11" fill="none">
          <path d="M11.07 0L4.6 6.46l-2.55-2.55L1 5l3.6 3.6L12.13 1.06z" fill={t.dark ? '#C6FF3D' : '#63A800'}/>
          <path d="M15 0L8.54 6.46 7.6 5.5 6.55 6.55l2 2L16 1.06z" fill={t.dark ? '#C6FF3D' : '#63A800'}/>
        </svg>
      )}
    </div>
  );
}

function MiniRing({ value, suffix, color, pct }) {
  const { t } = useGf();
  const size = 44, stroke = 3;
  const r = (size - stroke) / 2;
  const c = 2 * Math.PI * r;
  const off = c - (pct / 100) * c;
  return (
    <div style={{ position: 'relative', width: size, height: size }}>
      <svg width={size} height={size} style={{ transform: 'rotate(-90deg)' }}>
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke={t.line} strokeWidth={stroke} />
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke={color} strokeWidth={stroke}
                strokeLinecap="round" strokeDasharray={c} strokeDashoffset={off}/>
      </svg>
      <div style={{
        position: 'absolute', inset: 0,
        display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
        fontFamily: "'Bricolage Grotesque', Inter, sans-serif",
      }}>
        <span style={{ fontSize: 11, fontWeight: 800, color: t.text, lineHeight: 1 }}>{value}</span>
        <span style={{ fontSize: 7, color: t.muted, letterSpacing: '0.05em', marginTop: 1 }}>{suffix}</span>
      </div>
    </div>
  );
}

window.GfNav = GfNav;
window.GfHero = GfHero;
window.WhatsappGlyph = WhatsappGlyph;
window.useGf = useGf;
