// Sobella Landing — main app + Tweaks
const { useState: useLS, useEffect: useLE, useCallback: useLCB } = React;
function useWindowWidth() {
  const [w, setW] = useLS(window.innerWidth);
  useLE(() => {
    const h = () => setW(window.innerWidth);
    window.addEventListener('resize', h);
    return () => window.removeEventListener('resize', h);
  }, []);
  return w;
}

const LANDING_TWEAKS = /*EDITMODE-BEGIN*/{
  "accentColor": "#154734",
  "heroVariant": "warm",
  "showPhone": true,
  "heroHeadline": "Not giving something up."
}/*EDITMODE-END*/;

function useLandingTweaks(defaults) {
  const [t, setT] = useLS(defaults);
  useLE(() => {
    const onMsg = (e) => {
      const d = e.data || {};
      if (d.type === '__activate_edit_mode') setT(s => ({ ...s, __panelOpen: true }));
      if (d.type === '__deactivate_edit_mode') setT(s => ({ ...s, __panelOpen: false }));
    };
    window.addEventListener('message', onMsg);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', onMsg);
  }, []);
  const update = useLCB((patch) => {
    setT(s => ({ ...s, ...patch }));
    const persist = { ...patch };
    delete persist.__panelOpen;
    if (Object.keys(persist).length) {
      window.parent.postMessage({ type: '__edit_mode_set_keys', edits: persist }, '*');
    }
  }, []);
  return [t, update];
}

function LandingTweaksPanel({ tweaks, update }) {
  if (!tweaks.__panelOpen) return null;
  const row = (label, ctl) => (
    <div style={{ marginBottom: 16 }}>
      <div style={{
        fontSize: 10, fontWeight: 900, letterSpacing: '0.2em',
        textTransform: 'uppercase', color: 'rgba(255,255,255,0.5)',
        marginBottom: 8,
      }}>{label}</div>
      {ctl}
    </div>
  );
  const seg = (key, options) => (
    <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
      {options.map(o => (
        <button key={String(o.v)} onClick={() => update({ [key]: o.v })}
          style={{
            border: 'none', padding: '8px 12px', borderRadius: 9999,
            fontFamily: 'inherit', fontSize: 12, fontWeight: 600, cursor: 'pointer',
            background: tweaks[key] === o.v ? '#fff' : 'rgba(255,255,255,0.1)',
            color: tweaks[key] === o.v ? '#154734' : '#fff',
          }}>{o.l}</button>
      ))}
    </div>
  );
  const swatch = (key, options) => (
    <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
      {options.map(o => (
        <button key={o.v} onClick={() => update({ [key]: o.v })}
          title={o.l}
          style={{
            border: tweaks[key] === o.v ? '2px solid #fff' : '2px solid rgba(255,255,255,0.15)',
            width: 34, height: 34, borderRadius: 9999, cursor: 'pointer',
            background: o.v, padding: 0,
          }}/>
      ))}
    </div>
  );
  return (
    <div style={{
      position: 'fixed', bottom: 20, right: 20, zIndex: 100,
      width: 280, background: '#0B2017', color: '#fff',
      borderRadius: 24, padding: 20,
      boxShadow: '0 20px 60px rgba(0,0,0,0.35)',
      fontFamily: '-apple-system, system-ui, sans-serif',
    }}>
      <div style={{
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        marginBottom: 16,
      }}>
        <div style={{ fontWeight: 700, fontSize: 15 }}>Tweaks</div>
        <button onClick={() => update({ __panelOpen: false })}
          style={{
            background: 'rgba(255,255,255,0.1)', border: 'none', color: '#fff',
            width: 28, height: 28, borderRadius: 9999, cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M18 6L6 18M6 6l12 12"/></svg>
        </button>
      </div>
      {row('Hero accent color', swatch('accentColor', [
        { v: '#154734', l: 'Forest' },
        { v: '#E66B33', l: 'Terracotta' },
        { v: '#0B2017', l: 'Deep green' },
        { v: '#8B6F47', l: 'Oak' },
      ]))}
      {row('Hero mood', seg('heroVariant', [
        { v: 'warm', l: 'Cream' },
        { v: 'dark', l: 'Ceremonial' },
      ]))}
      {row('Show phone mockup', seg('showPhone', [
        { v: true, l: 'Yes' }, { v: false, l: 'No' },
      ]))}
      {row('Hero headline', (
        <input value={tweaks.heroHeadline}
          onChange={e => update({ heroHeadline: e.target.value })}
          style={{
            width: '100%', boxSizing: 'border-box',
            background: 'rgba(255,255,255,0.1)', border: 'none',
            borderRadius: 10, padding: '10px 12px',
            color: '#fff', fontFamily: 'inherit', fontSize: 13,
            outline: 'none',
          }}/>
      ))}
    </div>
  );
}

// ── Dark Hero variant ───────────────────────────────────────
function DarkHero({ accent, PhoneMock, showPhone, headline }) {
  const L = window.LandingTokens;
  const w = useWindowWidth();
  const mob = w < 768;
  return (
    <section style={{
      position: 'relative', overflow: 'hidden',
      background: L.deepGreen, color: '#fff',
      padding: mob ? '24px 20px 80px' : '20px 40px 100px',
    }}>
      <div style={{
        position: 'absolute', top: '-30%', left: '-10%',
        width: 900, height: 900, borderRadius: '50%',
        border: '1px solid rgba(255,255,255,0.05)',
      }}/>
      <div style={{
        position: 'absolute', top: '-10%', left: '5%',
        width: 600, height: 600, borderRadius: '50%',
        border: '1px solid rgba(255,255,255,0.07)',
      }}/>

      <div style={{
        maxWidth: 1240, margin: '0 auto', position: 'relative',
        display: 'grid',
        gridTemplateColumns: (!mob && showPhone) ? '1.05fr 0.95fr' : '1fr',
        gap: mob ? 0 : 60,
        alignItems: 'center', minHeight: mob ? 'auto' : 620,
      }}>
        <div>
          <h1 style={{
            marginTop: 0, fontSize: mob ? 40 : 72, fontWeight: 700,
            lineHeight: 0.98, letterSpacing: '-0.035em',
            color: '#fff', maxWidth: 640, textWrap: 'balance',
          }}>
            {headline}
            <br/>
            <span style={{ color: 'rgba(255,255,255,0.55)' }}>Becoming someone new.</span>
          </h1>

          <p style={{
            marginTop: 32, fontSize: mob ? 17 : 20, lineHeight: 1.5,
            color: 'rgba(255,255,255,0.7)', maxWidth: 520, textWrap: 'pretty',
          }}>
            Sobella is the private, unhurried companion for changing your
            relationship with alcohol — at your pace, on your terms,
            one quiet day at a time.
          </p>

          <div style={{ marginTop: 44, display: 'flex', flexDirection: mob ? 'column' : 'row', gap: 14, alignItems: mob ? 'stretch' : 'center', flexWrap: 'wrap' }}>
            <button style={{
              background: '#fff', color: L.primary,
              border: 'none', borderRadius: 9999,
              padding: '20px 32px', fontFamily: 'inherit',
              fontSize: 16, fontWeight: 700, cursor: 'pointer',
              boxShadow: '0 10px 24px rgba(0,0,0,0.25)',
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
            }}>
              Begin — it's free
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none"
                stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
                <path d="M5 12h14M12 5l7 7-7 7"/>
              </svg>
            </button>
            <button style={{
              background: 'transparent', color: '#fff',
              border: '1.5px solid rgba(255,255,255,0.25)', borderRadius: 9999,
              padding: '18.5px 28px', fontFamily: 'inherit',
              fontSize: 16, fontWeight: 600, cursor: 'pointer',
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
            }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M5 3l14 9-14 9z"/></svg>
              Watch the 40-second tour
            </button>
          </div>

          <div style={{ marginTop: 56, display: 'flex', gap: mob ? 32 : 48, flexWrap: 'wrap' }}>
            {[
              { n: '180K', l: 'Quiet days, logged' },
              { n: '4.9★', l: 'App Store average' },
              { n: '100%', l: 'Private by default' },
            ].map(s => (
              <div key={s.l}>
                <div style={{
                  fontSize: mob ? 24 : 32, fontWeight: 700, color: '#fff',
                  letterSpacing: '-0.02em', lineHeight: 1,
                }}>{s.n}</div>
                <div style={{
                  marginTop: 8, fontSize: 13, fontWeight: 500,
                  color: 'rgba(255,255,255,0.5)', letterSpacing: '0.02em',
                }}>{s.l}</div>
              </div>
            ))}
          </div>
        </div>

        {showPhone && (mob ? (
          <div style={{
            gridColumn: '1 / -1', marginTop: 36,
            display: 'flex', justifyContent: 'center',
            paddingTop: 16,
          }}>
            <div style={{
              transform: 'scale(0.82)',
              transformOrigin: 'top center',
              marginBottom: -874 * 0.18 * 0.5,
              filter: 'drop-shadow(0 32px 64px rgba(0,0,0,0.35))',
              flexShrink: 0,
            }}>
              <PhoneMock/>
            </div>
          </div>
        ) : (
          <div style={{
            position: 'relative', display: 'flex',
            justifyContent: 'center', alignItems: 'center',
          }}>
            <div style={{
              position: 'absolute', width: 520, height: 520,
              borderRadius: '50%', border: '1px solid rgba(255,255,255,0.1)',
            }}/>
            <div style={{
              position: 'absolute', width: 400, height: 400,
              borderRadius: '50%', border: '1px solid rgba(255,255,255,0.15)',
            }}/>
            <div style={{
              transform: 'scale(0.78) rotate(-2deg)',
              filter: 'drop-shadow(0 40px 80px rgba(0,0,0,0.4))',
            }}>
              <PhoneMock/>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

// ── Main App ────────────────────────────────────────────────
function LandingApp() {
  const [tweaks, updateTweaks] = useLandingTweaks(LANDING_TWEAKS);
  const PhoneMock = window.LandingPhoneMock;
  const isDark = tweaks.heroVariant === 'dark';

  return (
    <div data-screen-label="01 Landing" style={{
      fontFamily: '-apple-system, BlinkMacSystemFont, "SF Pro Text", "Helvetica Neue", "Inter", system-ui, sans-serif',
      color: '#1F1E1D',
    }}>
      <window.LandingNav variant={isDark ? 'dark' : 'light'}/>
      {isDark ? (
        <DarkHero
          accent={tweaks.accentColor}
          PhoneMock={PhoneMock}
          showPhone={tweaks.showPhone}
          headline={tweaks.heroHeadline}
        />
      ) : (
        <WarmHero
          accent={tweaks.accentColor}
          PhoneMock={PhoneMock}
          showPhone={tweaks.showPhone}
          headline={tweaks.heroHeadline}
        />
      )}
      <window.LandingPromise/>
      <window.LandingPillars/>
      <window.LandingAppScreens/>
      <window.LandingMeditations/>
      <window.LandingCeremony/>
      <window.LandingFounder/>
      <window.LandingHowItWorks/>
      <window.LandingFinalCTA/>
      <window.LandingFooter/>

      <LandingTweaksPanel tweaks={tweaks} update={updateTweaks}/>
    </div>
  );
}

// Wrap the original Hero to pass through tweak values
function WarmHero({ accent, PhoneMock, showPhone, headline }) {
  const L = window.LandingTokens;
  const w = useWindowWidth();
  const mob = w < 768;
  return (
    <section style={{
      position: 'relative', overflow: 'hidden',
      background: L.bg, padding: mob ? '24px 20px 80px' : '20px 40px 100px',
    }}>
      <div style={{
        position: 'absolute', top: -120, left: -120,
        width: 520, height: 520, borderRadius: '50%',
        border: '1px solid rgba(21,71,52,0.06)',
      }}/>
      <div style={{
        position: 'absolute', top: -40, left: -40,
        width: 360, height: 360, borderRadius: '50%',
        border: '1px solid rgba(21,71,52,0.08)',
      }}/>

      <div style={{
        maxWidth: 1240, margin: '0 auto', position: 'relative',
        display: 'grid',
        gridTemplateColumns: (!mob && showPhone) ? '1.05fr 0.95fr' : '1fr',
        gap: mob ? 0 : 60,
        alignItems: 'center', minHeight: mob ? 'auto' : 620,
      }}>
        <div>
          <h1 style={{
            marginTop: 0, fontSize: mob ? 40 : 72, fontWeight: 700,
            lineHeight: 0.98, letterSpacing: '-0.035em',
            color: L.charcoal, maxWidth: 640, textWrap: 'balance',
          }}>
            {headline}
            <br/>
            <span style={{ color: accent }}>Becoming someone new.</span>
          </h1>

          <p style={{
            marginTop: 32, fontSize: mob ? 17 : 20, lineHeight: 1.5,
            color: L.fg2, maxWidth: 520, textWrap: 'pretty',
          }}>
            Sobella is the private, unhurried companion for changing your
            relationship with alcohol — at your pace, on your terms,
            one quiet day at a time.
          </p>

          <div style={{ marginTop: 44, display: 'flex', flexDirection: mob ? 'column' : 'row', gap: 14, alignItems: mob ? 'stretch' : 'center', flexWrap: 'wrap' }}>
            <button style={{
              background: L.primary, color: '#fff',
              border: 'none', borderRadius: 9999,
              padding: '20px 32px', fontFamily: 'inherit',
              fontSize: 16, fontWeight: 700, cursor: 'pointer',
              boxShadow: '0 10px 24px -6px rgba(21,71,52,0.35)',
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
            }}>
              Begin — it's free
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none"
                stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
                <path d="M5 12h14M12 5l7 7-7 7"/>
              </svg>
            </button>
            <button style={{
              background: 'transparent', color: L.charcoal,
              border: `1.5px solid ${L.fg5}`, borderRadius: 9999,
              padding: '18.5px 28px', fontFamily: 'inherit',
              fontSize: 16, fontWeight: 600, cursor: 'pointer',
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
            }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M5 3l14 9-14 9z"/></svg>
              Watch the 40-second tour
            </button>
          </div>

          <div style={{ marginTop: 56, display: 'flex', gap: mob ? 32 : 48, flexWrap: 'wrap' }}>
            {[
              { n: '180K', l: 'Quiet days, logged' },
              { n: '4.9★', l: 'App Store average' },
              { n: '100%', l: 'Private by default' },
            ].map(s => (
              <div key={s.l}>
                <div style={{
                  fontSize: mob ? 24 : 32, fontWeight: 700, color: L.charcoal,
                  letterSpacing: '-0.02em', lineHeight: 1,
                }}>{s.n}</div>
                <div style={{
                  marginTop: 8, fontSize: 13, fontWeight: 500,
                  color: L.fg3, letterSpacing: '0.02em',
                }}>{s.l}</div>
              </div>
            ))}
          </div>
        </div>

        {showPhone && (mob ? (
          <div style={{
            gridColumn: '1 / -1', marginTop: 36,
            display: 'flex', justifyContent: 'center',
            paddingTop: 16,
          }}>
            <div style={{
              transform: 'scale(0.82)',
              transformOrigin: 'top center',
              marginBottom: -874 * 0.18 * 0.5,
              filter: 'drop-shadow(0 32px 64px rgba(21,71,52,0.18))',
              flexShrink: 0,
            }}>
              <PhoneMock/>
            </div>
          </div>
        ) : (
          <div style={{
            position: 'relative', display: 'flex',
            justifyContent: 'center', alignItems: 'center',
          }}>
            <div style={{
              position: 'absolute', inset: '10% -5%',
              background: 'radial-gradient(ellipse at center, rgba(21,71,52,0.10), transparent 60%)',
              filter: 'blur(20px)',
            }}/>
            <div style={{
              position: 'absolute', width: 520, height: 520,
              borderRadius: '50%', border: '1px solid rgba(21,71,52,0.12)',
            }}/>
            <div style={{
              position: 'absolute', width: 400, height: 400,
              borderRadius: '50%', border: '1px solid rgba(21,71,52,0.18)',
            }}/>
            <div style={{
              transform: 'scale(0.78) rotate(-2deg)',
              filter: 'drop-shadow(0 40px 80px rgba(21,71,52,0.18))',
            }}>
              <PhoneMock/>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

window.LandingApp = LandingApp;
