// landing.jsx — uri-jib.com 공개 랜딩 페이지

function LandingPage() {
  const { user } = useAuth();
  const [email, setEmail] = useState('');

  useEffect(() => {
    document.title = '우리집사기 — AI 부동산 매수 시그널 | uri-jib.com';
  }, []);

  const onSubmitEmail = (e) => {
    e.preventDefault();
    if (!email) return;
    window.UJTrack.track('lead_capture', { source: 'hero_form', email_domain: email.split('@')[1] || '' });
    navigate('/signup?email=' + encodeURIComponent(email));
  };

  return (
    <div style={{ minHeight: '100vh', background: T.bg, color: T.fg, fontFamily: T.font }}>
      <LandingNav user={user} />

      {/* HERO */}
      <section style={{ padding: '80px 24px 64px', maxWidth: 1200, margin: '0 auto' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1.1fr 0.9fr', gap: 64, alignItems: 'center' }}>
          <div>
            <div style={{
              display: 'inline-flex', alignItems: 'center', gap: 8,
              padding: '5px 12px', borderRadius: 999,
              background: T.hotBg, color: T.hot, border: '1px solid ' + T.hot + '40',
              fontSize: 12, fontFamily: T.mono, marginBottom: 24,
            }}>
              <LiveDot color={T.hot} label="" /> BETA · 국토부 RTMS 실시간 연동
            </div>
            <h1 style={{
              fontSize: 56, fontWeight: 800, lineHeight: 1.08,
              margin: 0, letterSpacing: '-0.02em',
            }}>
              AI가 알려주는<br/>
              <span style={{ color: T.hot }}>매수 적기.</span>
            </h1>
            <p style={{ fontSize: 17, color: T.fgDim, lineHeight: 1.6, marginTop: 20, maxWidth: 480 }}>
              국토부 실거래가 · 한국은행 금리 · GTX 호재 · 학군까지 12개 요인을 통합해
              지금 사도 되는 단지인지, 언제 사야 가장 싼지 알려드립니다.
            </p>

            <form onSubmit={onSubmitEmail} style={{ marginTop: 32, display: 'flex', gap: 8, maxWidth: 480 }}>
              <input
                type="email"
                required
                placeholder="이메일을 입력하세요"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                onFocus={() => window.UJTrack.track('field_focus', { field: 'hero_email' })}
                style={{
                  flex: 1, padding: '14px 16px', borderRadius: 4,
                  background: T.card, color: T.fg, fontSize: 14,
                  border: '1px solid ' + T.line, outline: 'none', fontFamily: T.font,
                }}
              />
              <button
                type="submit"
                data-track="hero_cta_start"
                style={{
                  padding: '14px 24px', borderRadius: 4,
                  background: T.hot, color: T.bg, border: 'none',
                  fontSize: 14, fontWeight: 700, cursor: 'pointer',
                  fontFamily: T.font, whiteSpace: 'nowrap',
                }}>
                무료로 시작하기 →
              </button>
            </form>
            <div style={{ display: 'flex', gap: 20, marginTop: 18, fontSize: 12, color: T.fgMuted, fontFamily: T.mono }}>
              <span>✓ 신용카드 불필요</span>
              <span>✓ 즉시 가입</span>
              <span>✓ 12,847명 사용 중</span>
            </div>
          </div>

          {/* Hero visual */}
          <HeroPreview />
        </div>
      </section>

      {/* STATS BAR */}
      <section style={{ background: T.bgAlt, borderTop: '1px solid ' + T.line, borderBottom: '1px solid ' + T.line, padding: '24px 0' }}>
        <div style={{ maxWidth: 1200, margin: '0 auto', display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 32, padding: '0 24px' }}>
          {[
            ['12,847', '활성 사용자'],
            ['1.2M+', '실거래 데이터'],
            ['86%', '예측 적중률'],
            ['24/7', 'RTMS 실시간'],
          ].map(([v, k]) => (
            <div key={k}>
              <div className="uj-num" style={{ fontSize: 32, fontWeight: 700, color: T.hot }}>{v}</div>
              <div style={{ fontSize: 12, color: T.fgMuted, marginTop: 4 }}>{k}</div>
            </div>
          ))}
        </div>
      </section>

      {/* FEATURES */}
      <section id="features" style={{ padding: '96px 24px', maxWidth: 1200, margin: '0 auto' }}>
        <SectionHeading kicker="FEATURES" title="다른 부동산 앱이 보여주지 못하는 것" />
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 24, marginTop: 48 }}>
          <FeatureCard
            tag="01" title="AI 매수 시그널"
            desc="단순 시세가 아니라 '지금 사도 되는지' BUY/WATCH/HOLD/AVOID 4단계로 알려드립니다. 12개 요인 SHAP 분석 포함."
            color={T.hot}
          />
          <FeatureCard
            tag="02" title="언제 사야 가장 싼지"
            desc="향후 12개월 가격 밴드 예측. 최적 매수 시점(月)과 신뢰도(%)를 제시합니다."
            color={T.up}
          />
          <FeatureCard
            tag="03" title="대출·세금까지 한 번에"
            desc="DTI/DSR 한도 계산, 취득세·재산세·양도세 시뮬레이션. 실제 가능 매수가까지 보여드립니다."
            color={T.info}
          />
          <FeatureCard
            tag="04" title="실시간 호재 알림"
            desc="GTX 개통, 재건축 단계 변화, DSR 규제 등 단지에 영향을 주는 뉴스 푸시."
            color={T.ai}
          />
          <FeatureCard
            tag="05" title="지역 비교"
            desc="강남·분당·수원 같은 후보 지역을 8개 지표로 한눈에 비교."
            color={T.up}
          />
          <FeatureCard
            tag="06" title="포트폴리오 추적"
            desc="관심 단지 목록과 보유 매물을 한 화면에. 가격 변동·시그널 변화 자동 추적."
            color={T.hot}
          />
        </div>
      </section>

      {/* HOW IT WORKS */}
      <section style={{ background: T.bgAlt, borderTop: '1px solid ' + T.line, padding: '96px 24px' }}>
        <div style={{ maxWidth: 1200, margin: '0 auto' }}>
          <SectionHeading kicker="HOW IT WORKS" title="3분만에 시작" />
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 24, marginTop: 48 }}>
            {[
              { step: '01', title: '가입 + 온보딩', desc: '카카오·네이버·구글·애플 또는 이메일로 30초.\n관심 지역·예산을 알려주세요.' },
              { step: '02', title: 'AI 분석 결과 확인', desc: '관심 단지·지역마다 매수 시그널과\n향후 12개월 가격 예측을 받습니다.' },
              { step: '03', title: '알림으로 적기 포착', desc: '시그널이 BUY로 바뀌면 푸시.\n매수 적기를 놓치지 않습니다.' },
            ].map((s) => (
              <div key={s.step} style={{
                background: T.card, border: '1px solid ' + T.line, borderRadius: 6, padding: 28,
              }}>
                <div style={{ fontFamily: T.mono, fontSize: 36, fontWeight: 700, color: T.hot, lineHeight: 1 }}>{s.step}</div>
                <div style={{ fontSize: 18, fontWeight: 600, marginTop: 16 }}>{s.title}</div>
                <div style={{ fontSize: 13, color: T.fgDim, marginTop: 8, lineHeight: 1.6, whiteSpace: 'pre-line' }}>{s.desc}</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* DATA SOURCES */}
      <section style={{ padding: '64px 24px', maxWidth: 1200, margin: '0 auto' }}>
        <div style={{ fontSize: 11, fontFamily: T.mono, color: T.fgMuted, letterSpacing: 1.5, textAlign: 'center' }}>
          TRUSTED DATA SOURCES
        </div>
        <div style={{ display: 'flex', justifyContent: 'center', gap: 48, marginTop: 24, flexWrap: 'wrap', opacity: 0.7 }}>
          {['국토교통부 RTMS', '한국은행 ECOS', 'KB부동산', '한국부동산원', '통계청', 'data.go.kr'].map((s) => (
            <div key={s} style={{ fontFamily: T.mono, fontSize: 13, color: T.fgDim, letterSpacing: 0.5 }}>{s}</div>
          ))}
        </div>
      </section>

      {/* CTA */}
      <section style={{ padding: '96px 24px', textAlign: 'center', borderTop: '1px solid ' + T.line }}>
        <h2 style={{ fontSize: 40, fontWeight: 800, margin: 0, letterSpacing: '-0.01em' }}>
          이번 사이클은 놓치지 마세요.
        </h2>
        <p style={{ fontSize: 16, color: T.fgDim, marginTop: 16 }}>지금 가입하면 평생 무료.</p>
        <div style={{ display: 'flex', gap: 12, justifyContent: 'center', marginTop: 32 }}>
          <a href="#/signup" data-track="cta_signup_bottom" style={primaryBtn}>가입하고 시작 →</a>
          <a href="#/login" data-track="cta_login_bottom" style={ghostBtn}>이미 계정이 있어요</a>
        </div>
      </section>

      <LandingFooter />
      <style>{`
        @keyframes ujfadeup{from{transform:translateX(-50%) translateY(8px);opacity:0}to{transform:translateX(-50%) translateY(0);opacity:1}}
      `}</style>
    </div>
  );
}

function LandingNav({ user }) {
  return (
    <header style={{
      position: 'sticky', top: 0, zIndex: 50,
      background: 'rgba(11,18,32,0.85)', backdropFilter: 'blur(12px)',
      borderBottom: '1px solid ' + T.line,
    }}>
      <div style={{
        maxWidth: 1200, margin: '0 auto', padding: '14px 24px',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <a href="#/" data-track="nav_logo" style={{ display: 'flex', alignItems: 'center', gap: 10, textDecoration: 'none' }}>
          <Logo size={28} />
          <span style={{ fontSize: 16, fontWeight: 700, color: T.fg }}>우리집사기</span>
          <span style={{ fontSize: 10, color: T.fgMuted, fontFamily: T.mono, padding: '2px 6px', border: '1px solid ' + T.line, borderRadius: 3 }}>BETA</span>
        </a>
        <nav style={{ display: 'flex', alignItems: 'center', gap: 28 }}>
          <a href="#features" data-track="nav_features" style={navLink}>기능</a>
          <a href="#/pricing" data-track="nav_pricing" style={navLink}>요금</a>
          <a href="#/about" data-track="nav_about" style={navLink}>회사</a>
          {user ? (
            <a href="#/app/dashboard" data-track="nav_to_app" style={primaryBtn}>앱 열기 →</a>
          ) : (
            <>
              <a href="#/login" data-track="nav_login" style={{ ...navLink, color: T.fg }}>로그인</a>
              <a href="#/signup" data-track="nav_signup_top" style={primaryBtn}>무료 가입</a>
            </>
          )}
        </nav>
      </div>
    </header>
  );
}

function LandingFooter() {
  return (
    <footer style={{ borderTop: '1px solid ' + T.line, background: T.bgAlt, padding: '48px 24px 32px' }}>
      <div style={{ maxWidth: 1200, margin: '0 auto' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1.5fr repeat(3, 1fr)', gap: 32 }}>
          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <Logo size={24} />
              <span style={{ fontWeight: 700 }}>우리집사기</span>
            </div>
            <div style={{ fontSize: 12, color: T.fgMuted, marginTop: 12, lineHeight: 1.6 }}>
              AI가 알려주는 매수 적기.<br/>
              uri-jib.com
            </div>
          </div>
          <FooterCol title="제품" links={[['앱 둘러보기', '#/app/dashboard'], ['요금', '#/pricing'], ['릴리즈 노트', '#/changelog']]} />
          <FooterCol title="회사" links={[['소개', '#/about'], ['블로그', '#/blog'], ['채용', '#/careers']]} />
          <FooterCol title="법적 고지" links={[['이용약관', '#/terms'], ['개인정보처리방침', '#/privacy'], ['투자 면책', '#/disclaimer']]} />
        </div>
        <div style={{ marginTop: 40, paddingTop: 24, borderTop: '1px solid ' + T.line, display: 'flex', justifyContent: 'space-between', fontSize: 11, color: T.fgFaint, fontFamily: T.mono }}>
          <span>© 2026 우리집사기. All rights reserved.</span>
          <span>본 서비스는 투자 자문이 아닌 정보 제공입니다.</span>
        </div>
      </div>
    </footer>
  );
}

function FooterCol({ title, links }) {
  return (
    <div>
      <div style={{ fontSize: 11, color: T.fgDim, fontFamily: T.mono, letterSpacing: 1.2, textTransform: 'uppercase' }}>{title}</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 14 }}>
        {links.map(([label, href]) => (
          <a key={label} href={href} data-track="footer_link" data-track-link={label}
            style={{ fontSize: 13, color: T.fgDim, textDecoration: 'none' }}>{label}</a>
        ))}
      </div>
    </div>
  );
}

function FeatureCard({ tag, title, desc, color }) {
  return (
    <div style={{
      background: T.card, border: '1px solid ' + T.line, borderRadius: 6, padding: 24,
      transition: 'border .2s, transform .2s',
    }}
      onMouseEnter={(e) => { e.currentTarget.style.borderColor = color + '60'; e.currentTarget.style.transform = 'translateY(-2px)'; }}
      onMouseLeave={(e) => { e.currentTarget.style.borderColor = T.line; e.currentTarget.style.transform = 'none'; }}
    >
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <div style={{ width: 6, height: 6, borderRadius: 3, background: color, boxShadow: '0 0 8px ' + color }} />
        <div style={{ fontSize: 11, fontFamily: T.mono, color, letterSpacing: 1 }}>{tag}</div>
      </div>
      <div style={{ fontSize: 17, fontWeight: 600, marginTop: 14 }}>{title}</div>
      <div style={{ fontSize: 13, color: T.fgDim, marginTop: 8, lineHeight: 1.6 }}>{desc}</div>
    </div>
  );
}

function SectionHeading({ kicker, title }) {
  return (
    <div style={{ textAlign: 'center' }}>
      <div style={{ fontSize: 11, fontFamily: T.mono, color: T.hot, letterSpacing: 1.5 }}>{kicker}</div>
      <h2 style={{ fontSize: 36, fontWeight: 800, margin: '12px 0 0', letterSpacing: '-0.01em' }}>{title}</h2>
    </div>
  );
}

function Logo({ size = 32 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 512 512" style={{ flexShrink: 0 }}>
      <rect width="512" height="512" rx="100" fill="#0B1220"/>
      <rect x="96" y="96" width="320" height="320" rx="58" fill="#FFB020"/>
      <text x="256" y="335" fontFamily="-apple-system, system-ui, sans-serif" fontWeight="800" fontSize="200" fill="#0B1220" textAnchor="middle">우</text>
      <circle cx="396" cy="116" r="26" fill="#1FB57A"/>
    </svg>
  );
}

// Hero preview — sneak peek of the actual app
function HeroPreview() {
  const apt = APTS[4]; // 대치 은마
  return (
    <div style={{
      background: T.card, border: '1px solid ' + T.line, borderRadius: 8,
      padding: 20, position: 'relative',
      boxShadow: '0 24px 80px rgba(0,0,0,0.5), 0 0 0 1px ' + T.lineHi,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <ScoreRing score={apt.score} size={48} stroke={4} />
          <div>
            <div style={{ fontSize: 14, fontWeight: 600 }}>{apt.name}</div>
            <div style={{ fontSize: 11, color: T.fgMuted }}>{apt.region}</div>
          </div>
        </div>
        <SignalBadge kind={apt.signal} />
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 12 }}>
        <div>
          <div style={{ fontSize: 10, color: T.fgMuted, fontFamily: T.mono, letterSpacing: 1 }}>CURRENT</div>
          <div className="uj-num" style={{ fontSize: 24, fontWeight: 700 }}>{won(apt.currentPrice)}</div>
        </div>
        <Delta value={apt.delta1y} size={14} />
      </div>
      <div style={{ background: T.cardLo, borderRadius: 4, padding: 12 }}>
        <LineChart
          history={apt.history.slice(-12)}
          forecast={forecast(apt.currentPrice, 8, 0.005, 0.025).forecast}
          band={forecast(apt.currentPrice, 8, 0.005, 0.025).band}
          width={420} height={140}
        />
      </div>
      <div style={{ marginTop: 12, padding: 12, background: T.hotBg, border: '1px solid ' + T.hot + '40', borderRadius: 4 }}>
        <div style={{ fontSize: 10, fontFamily: T.mono, color: T.hot, letterSpacing: 1 }}>AI BUY SIGNAL · 신뢰도 {apt.confidence}%</div>
        <div style={{ fontSize: 13, fontWeight: 600, marginTop: 4 }}>
          최적 매수: <span className="uj-num">{apt.bestBuyMonth}</span>
          <span style={{ color: T.fgMuted, marginLeft: 8 }}>적정가 {won(apt.targetPrice)}</span>
        </div>
      </div>
    </div>
  );
}

// Shared styles
const navLink = {
  fontSize: 13, color: T.fgDim, textDecoration: 'none',
  fontFamily: T.font, padding: '6px 4px',
};
const primaryBtn = {
  display: 'inline-flex', alignItems: 'center', gap: 6,
  padding: '10px 18px', borderRadius: 4,
  background: T.hot, color: T.bg, textDecoration: 'none',
  fontSize: 13, fontWeight: 700, fontFamily: T.font,
  border: 'none', cursor: 'pointer',
};
const ghostBtn = {
  display: 'inline-flex', alignItems: 'center', gap: 6,
  padding: '10px 18px', borderRadius: 4,
  background: 'transparent', color: T.fg, textDecoration: 'none',
  fontSize: 13, fontWeight: 600, fontFamily: T.font,
  border: '1px solid ' + T.lineHi, cursor: 'pointer',
};

Object.assign(window, { LandingPage, Logo, primaryBtn, ghostBtn, navLink });
