// Keynara Hero — bold typographic hero + working inline chat agent + property card stream
const { useState: useS, useEffect: useE, useRef: useR, useMemo: useM } = React;

// Mock city dataset
const MOCK_LISTINGS = [
  { id: 1, city: 'Wien', zip: '1120', type: 'Kauf', rooms: 3, area: 110, price: 498000, rate: null, match: 96, tag: 'Top Match', note: 'Ruhig, Balkon West' },
  { id: 2, city: 'Wien', zip: '1090', type: 'Kauf', rooms: 3, area: 95, price: 475000, rate: null, match: 91, tag: 'Gute Lage', note: 'U4/U6, renoviert' },
  { id: 3, city: 'Wien', zip: '1030', type: 'Kauf', rooms: 3, area: 102, price: 489000, rate: null, match: 88, tag: 'Wertstabil', note: 'Altbau, hohe Decken' },
  { id: 4, city: 'Berlin', zip: '10117', type: 'Miete', rooms: 2, area: 62, price: 1490, rate: 'mtl.', match: 94, tag: 'Neu', note: 'Mitte, ab Mai' },
  { id: 5, city: 'Berlin', zip: '10115', type: 'Miete', rooms: 2, area: 58, price: 1390, rate: 'mtl.', match: 90, tag: 'Beliebt', note: 'Rosenthaler Platz' },
  { id: 6, city: 'Berlin', zip: '10178', type: 'Miete', rooms: 2, area: 65, price: 1550, rate: 'mtl.', match: 87, tag: 'Direktlage', note: 'Hackescher Markt' },
  { id: 7, city: 'Milano', zip: '20121', type: 'Investment', rooms: 3, area: 85, price: 620000, rate: null, match: 93, tag: '4.3% Rendite', note: 'Brera, vermietet' },
  { id: 8, city: 'Milano', zip: '20154', type: 'Investment', rooms: 2, area: 62, price: 420000, rate: null, match: 89, tag: '4.1% Rendite', note: 'Isola, Nähe Tram' },
  { id: 9, city: 'Milano', zip: '20145', type: 'Investment', rooms: 3, area: 90, price: 580000, rate: null, match: 85, tag: '3.9% Rendite', note: 'Sempione, Park' },
];

function detectScenario(text) {
  const s = text.toLowerCase();
  if (/milano|mail|invest|rendite|yield|milan/.test(s)) return 'milan';
  if (/berlin|miete|rent/.test(s)) return 'berlin';
  return 'vienna';
}
function scenarioListings(key) {
  if (key === 'berlin') return MOCK_LISTINGS.slice(3, 6);
  if (key === 'milan') return MOCK_LISTINGS.slice(6, 9);
  return MOCK_LISTINGS.slice(0, 3);
}

function Hero({ t, lang, onFocus }) {
  // Chat state
  const [stage, setStage] = useS('idle'); // idle | typing-user | agent-asking | typing-user-2 | agent-thinking | results
  const [value, setValue] = useS('');
  const [messages, setMessages] = useS([]);
  const [listings, setListings] = useS([]);
  const [activeSuggest, setActiveSuggest] = useS(0);
  const bodyRef = useR(null);

  useE(() => {
    if (bodyRef.current) bodyRef.current.scrollTop = bodyRef.current.scrollHeight;
  }, [messages, stage]);

  // Idle demo: rotate suggestions
  useE(() => {
    if (stage !== 'idle') return;
    const id = setInterval(() => setActiveSuggest(i => (i + 1) % t.hero.suggestions.length), 2800);
    return () => clearInterval(id);
  }, [stage, t.hero.suggestions.length]);

  function submit(customText) {
    const text = (customText ?? value).trim();
    if (!text) return;
    setValue('');
    const scenario = detectScenario(text);

    setMessages([{ role: 'user', text }]);
    setStage('agent-asking');

    setTimeout(() => {
      const ask = lang === 'de'
        ? 'Verstanden. Kauf oder Miete? In welcher Stadt und mit welchem Budget?'
        : 'Got it. Buy or rent? Which city and what budget?';
      setMessages(m => [...m, { role: 'agent', text: ask }]);
    }, 900);

    setTimeout(() => {
      const reply = lang === 'de' ? 'Budget steht, Lage passt — zeig mir die Treffer.' : 'Budget set, location fits — show me the matches.';
      setMessages(m => [...m, { role: 'user', text: reply }]);
    }, 2400);

    setTimeout(() => {
      setStage('agent-thinking');
    }, 3000);

    setTimeout(() => {
      const intro = lang === 'de'
        ? 'Hier sind drei Treffer, nach Relevanz gewichtet:'
        : 'Here are three matches, weighted by relevance:';
      setMessages(m => [...m, { role: 'agent', text: intro, withResults: true }]);
      setListings(scenarioListings(scenario));
      setStage('results');
    }, 4200);
  }

  function reset() {
    setMessages([]);
    setListings([]);
    setValue('');
    setStage('idle');
  }

  return (
    <section id="home" style={{ position: 'relative', paddingTop: 120, paddingBottom: 80, overflow: 'hidden' }}>
      {/* Background grid */}
      <BgGrid />
      <div className="container" style={{ position: 'relative' }}>
        <div className="hero-grid" style={{ display: 'grid', gridTemplateColumns: '1.1fr 1fr', gap: 80, alignItems: 'center' }}>
          {/* LEFT: statement */}
          <div>
            <Reveal>
              <div className="eyebrow">{t.hero.eyebrow}</div>
            </Reveal>
            <Reveal delay={80}>
              <h1 className="display" style={{ marginTop: 24, marginBottom: 24, color: 'var(--navy)' }}>
                {t.hero.title_1}<br/>
                {t.hero.title_2}<br/>
                <span style={{ position: 'relative', display: 'inline-block' }}>
                  {t.hero.title_3}
                  <span style={{
                    position: 'absolute', right: -18, bottom: 18,
                    width: 12, height: 12, borderRadius: '50%',
                    background: 'var(--mint)',
                    boxShadow: '0 0 0 6px rgba(0,201,167,0.14)',
                  }}/>
                </span>
              </h1>
            </Reveal>
            <Reveal delay={160}>
              <p className="body-lg" style={{ maxWidth: 520, fontSize: 21, color: 'var(--slate)' }}>
                {t.hero.sub}
              </p>
            </Reveal>
            <Reveal delay={240}>
              <div style={{ display: 'flex', gap: 12, marginTop: 32, flexWrap: 'wrap' }}>
                <button className="btn btn--primary" onClick={() => onFocus && onFocus()}>
                  {t.hero.cta_primary} <Icon.arrow />
                </button>
                <button className="btn btn--secondary">{t.hero.cta_secondary}</button>
              </div>
            </Reveal>
            <Reveal delay={340}>
              <div style={{ marginTop: 48, display: 'flex', gap: 40, alignItems: 'center', flexWrap: 'wrap' }}>
                <Stat v="3–5" l={lang === 'de' ? 'Treffer statt 1.000+' : 'matches, not 1,000+'} />
                <Stat v="< 60s" l={lang === 'de' ? 'bis zur Entscheidung' : 'to decision'} />
                <Stat v="4 Länder" l={lang === 'de' ? 'DACH & Italien' : 'DACH & Italy'} />
              </div>
            </Reveal>
          </div>

          {/* RIGHT: chat agent */}
          <Reveal delay={200}>
            <ChatAgent
              t={t} lang={lang}
              stage={stage} setStage={setStage}
              messages={messages} setMessages={setMessages}
              listings={listings}
              value={value} setValue={setValue}
              submit={submit} reset={reset}
              activeSuggest={activeSuggest}
              bodyRef={bodyRef}
            />
          </Reveal>
        </div>
      </div>
      <style>{`
        @media (max-width: 1000px) {
          .hero-grid { grid-template-columns: 1fr !important; gap: 48px !important; }
        }
      `}</style>
    </section>
  );
}

function Stat({ v, l }) {
  return (
    <div>
      <div style={{ fontFamily: 'DM Sans', fontSize: 28, fontWeight: 400, color: 'var(--navy)', letterSpacing: '-0.02em' }}>{v}</div>
      <div style={{ fontSize: 13, color: 'var(--slate)', marginTop: 4 }}>{l}</div>
    </div>
  );
}

function BgGrid() {
  return (
    <>
      <div style={{
        position: 'absolute', inset: 0,
        backgroundImage: 'linear-gradient(var(--line) 1px, transparent 1px), linear-gradient(90deg, var(--line) 1px, transparent 1px)',
        backgroundSize: '80px 80px',
        maskImage: 'radial-gradient(ellipse 80% 60% at 50% 20%, black, transparent)',
        WebkitMaskImage: 'radial-gradient(ellipse 80% 60% at 50% 20%, black, transparent)',
        opacity: 0.5,
        pointerEvents: 'none',
      }}/>
      <div style={{
        position: 'absolute', top: 200, right: -60, width: 360, height: 360,
        background: 'radial-gradient(circle, rgba(0,201,167,0.12), transparent 70%)',
        pointerEvents: 'none',
      }}/>
    </>
  );
}

function ChatAgent({ t, lang, stage, setStage, messages, setMessages, listings, value, setValue, submit, reset, activeSuggest, bodyRef }) {
  const inputRef = useR(null);

  return (
    <div style={{
      background: 'white',
      borderRadius: 24,
      border: '1px solid var(--line)',
      boxShadow: '0 24px 60px -20px rgba(26,43,60,0.20), 0 0 0 1px rgba(26,43,60,0.02)',
      overflow: 'hidden',
      position: 'relative',
    }}>
      {/* Header */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '16px 20px', borderBottom: '1px solid var(--line)',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <LogoMark size={28} />
          <div>
            <div style={{ fontFamily: 'DM Sans', fontSize: 14, fontWeight: 500, color: 'var(--navy)' }}>Keynara Agent</div>
            <div style={{ fontSize: 11, color: 'var(--slate)', display: 'flex', alignItems: 'center', gap: 6 }}>
              <span style={{ width: 6, height: 6, borderRadius: '50%', background: '#00C9A7', animation: 'pulse-dot 2s infinite' }}></span>
              {t.hero.live}
            </div>
          </div>
        </div>
        {stage !== 'idle' && (
          <button onClick={reset} style={{
            fontSize: 12, color: 'var(--slate)', letterSpacing: '0.08em',
            textTransform: 'uppercase', padding: '6px 10px', borderRadius: 999,
            background: 'var(--fog)', fontWeight: 500,
          }}>{lang === 'de' ? 'Neu' : 'Reset'}</button>
        )}
      </div>

      {/* Chat body */}
      <div ref={bodyRef} style={{
        minHeight: 420, maxHeight: 520, overflowY: 'auto',
        padding: 24, display: 'flex', flexDirection: 'column', gap: 12,
        background: 'linear-gradient(180deg, white, #FAFBFC)',
      }}>
        {stage === 'idle' && <AgentWelcome t={t} lang={lang} />}
        {messages.map((m, i) => (
          <Message key={i} role={m.role} text={m.text}>
            {m.withResults && <ResultsList listings={listings} lang={lang} />}
          </Message>
        ))}
        {(stage === 'agent-asking' || stage === 'agent-thinking') && <TypingBubble label={lang === 'de' ? (stage === 'agent-thinking' ? 'sucht Treffer…' : 'schreibt…') : (stage === 'agent-thinking' ? 'finding matches…' : 'typing…')} />}
      </div>

      {/* Composer */}
      <div style={{ padding: 16, borderTop: '1px solid var(--line)', background: 'white' }}>
        {stage === 'idle' && (
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 12 }}>
            {t.hero.suggestions.map((s, i) => (
              <button key={i}
                onClick={() => submit(s)}
                style={{
                  padding: '8px 14px',
                  borderRadius: 999,
                  background: i === activeSuggest ? 'var(--navy)' : 'var(--fog)',
                  color: i === activeSuggest ? 'white' : 'var(--slate)',
                  fontSize: 12,
                  fontWeight: 500,
                  border: '1px solid ' + (i === activeSuggest ? 'var(--navy)' : 'transparent'),
                  transition: 'all 300ms',
                }}>
                {s}
              </button>
            ))}
          </div>
        )}
        <form onSubmit={(e) => { e.preventDefault(); submit(); }} style={{
          display: 'flex', alignItems: 'center', gap: 8,
          background: 'var(--fog)', borderRadius: 16, padding: 6,
          border: '1px solid transparent', transition: 'border-color 180ms',
        }}
        onFocus={(e) => e.currentTarget.style.borderColor = 'var(--mint)'}
        onBlur={(e) => e.currentTarget.style.borderColor = 'transparent'}
        >
          <input
            ref={inputRef}
            value={value}
            onChange={(e) => setValue(e.target.value)}
            placeholder={t.hero.chat_placeholder}
            style={{
              flex: 1, padding: '12px 14px', background: 'transparent',
              border: 'none', outline: 'none', fontFamily: 'inherit', fontSize: 15, color: 'var(--navy)',
            }}
          />
          <button type="submit" className="btn btn--primary" style={{ padding: '12px 18px' }} aria-label="send">
            <Icon.send />
          </button>
        </form>
      </div>
    </div>
  );
}

function AgentWelcome({ t, lang }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      <Message role="agent" text={lang === 'de'
        ? 'Hallo. Ich bin Keynara — dein Entscheidungs-Agent für Immobilien. Beschreibe in deinen Worten, was du suchst.'
        : 'Hi. I\'m Keynara — your decision agent for real estate. Tell me in your own words what you\'re looking for.'
      }/>
      <Message role="agent" text={lang === 'de'
        ? 'Kauf oder Miete? In welcher Stadt suchst du?'
        : 'Buy or rent? Which city are you looking in?'
      }/>
    </div>
  );
}

function Message({ role, text, children }) {
  const isUser = role === 'user';
  return (
    <div style={{
      display: 'flex', justifyContent: isUser ? 'flex-end' : 'flex-start',
      animation: 'slideIn 300ms ease',
    }}>
      <div style={{ maxWidth: '82%', display: 'flex', flexDirection: 'column', alignItems: isUser ? 'flex-end' : 'flex-start' }}>
        <div style={{
          padding: '12px 16px',
          borderRadius: isUser ? '16px 16px 4px 16px' : '16px 16px 16px 4px',
          background: isUser ? 'var(--navy)' : 'var(--fog)',
          color: isUser ? 'white' : 'var(--navy)',
          fontSize: 14.5, lineHeight: 1.5,
        }}>
          {text}
        </div>
        {children && <div style={{ width: '100%', marginTop: 12 }}>{children}</div>}
      </div>
    </div>
  );
}

function TypingBubble({ label }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, animation: 'slideIn 300ms ease' }}>
      <div style={{
        padding: '14px 16px', borderRadius: '16px 16px 16px 4px', background: 'var(--fog)',
        display: 'inline-flex', gap: 4,
      }}>
        {[0, 1, 2].map(i => (
          <span key={i} style={{
            width: 6, height: 6, borderRadius: '50%', background: 'var(--slate)',
            animation: `typingBounce 1.2s infinite ${i * 0.2}s`,
          }}/>
        ))}
      </div>
      <span style={{ fontSize: 12, color: 'var(--slate)' }}>{label}</span>
    </div>
  );
}

function ResultsList({ listings, lang }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
      {listings.map((l, i) => (
        <ResultCard key={l.id} l={l} idx={i} lang={lang}/>
      ))}
    </div>
  );
}

function ResultCard({ l, idx, lang }) {
  const priceStr = l.rate
    ? `${l.price.toLocaleString(lang === 'de' ? 'de-DE' : 'en-US')} € / ${lang === 'de' ? 'Monat' : 'month'}`
    : `${l.price.toLocaleString(lang === 'de' ? 'de-DE' : 'en-US')} €`;
  return (
    <div style={{
      background: 'white', border: '1px solid var(--line)',
      borderRadius: 14, padding: 14,
      display: 'flex', gap: 14, alignItems: 'center',
      animation: `slideIn 400ms ease ${idx * 120}ms both`,
    }}>
      <PlaceholderImage type={l.type}/>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4, flexWrap: 'wrap' }}>
          <span style={{
            fontSize: 10, letterSpacing: '0.08em', textTransform: 'uppercase',
            padding: '2px 8px', borderRadius: 999, background: 'var(--mint-soft)', color: 'var(--mint-dark)', fontWeight: 600,
          }}>{l.match}% Match</span>
          <span style={{ fontSize: 11, color: 'var(--slate)' }}>{l.tag}</span>
        </div>
        <div style={{ fontFamily: 'DM Sans', fontSize: 15, fontWeight: 500, color: 'var(--navy)', letterSpacing: '-0.01em' }}>
          {l.zip} {l.city} · {l.rooms} {lang === 'de' ? 'Zi' : 'rms'} · {l.area} m²
        </div>
        <div style={{ fontSize: 12, color: 'var(--slate)', marginTop: 2 }}>{l.note}</div>
      </div>
      <div style={{ textAlign: 'right' }}>
        <div style={{ fontFamily: 'DM Sans', fontSize: 15, fontWeight: 500, color: 'var(--navy)' }}>{priceStr}</div>
        <button style={{
          marginTop: 4, fontSize: 11, color: 'var(--mint-dark)',
          textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 600,
        }}>{lang === 'de' ? 'Ansehen' : 'View'} →</button>
      </div>
    </div>
  );
}

function PlaceholderImage({ type }) {
  // Subtle striped svg placeholder colored by brand
  const colors = {
    Kauf: ['#1A2B3C', '#4A6278'],
    Miete: ['#4A6278', '#00C9A7'],
    Investment: ['#00C9A7', '#1A2B3C'],
  }[type] || ['#1A2B3C', '#4A6278'];
  return (
    <div style={{
      width: 56, height: 56, borderRadius: 10, overflow: 'hidden', flexShrink: 0,
      background: colors[0],
      position: 'relative',
    }}>
      <svg width="100%" height="100%" viewBox="0 0 56 56" style={{ opacity: 0.95 }}>
        <defs>
          <pattern id={`p-${type}`} width="8" height="8" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">
            <rect width="4" height="8" fill={colors[1]} opacity="0.35"/>
          </pattern>
        </defs>
        <rect width="56" height="56" fill={`url(#p-${type})`}/>
        <path d="M10 36l10-8 8 6 10-10 10 8v14H10z" fill="white" opacity="0.15"/>
      </svg>
    </div>
  );
}

Object.assign(window, { Hero });
