const { useState, useEffect, useRef } = React;

// i18n
const i18n = {
  en: {
    nav: ['Projects','Philosophy','Team','Awards','Contact'],
    heroTag: 'Est. 2008 · Architecture & Design',
    heroTitle: 'Shaping the Horizon',
    heroSub: 'We design spaces that transcend time. Where light meets form, and vision becomes reality.',
    heroCta: 'View Projects',
    projectsTitle: 'Selected Projects',
    projectsDesc: 'A curated selection of our most transformative works across three continents.',
    philosophyTitle: 'Our Philosophy',
    philosophyText: 'Architecture is not merely about constructing buildings. It is about crafting experiences, shaping communities, and leaving a legacy that endures beyond our lifetimes. Every line we draw, every material we choose, serves a purpose greater than aesthetics alone.',
    teamTitle: 'The Team',
    teamDesc: 'Eight visionaries united by a shared commitment to architectural excellence.',
    awardsTitle: 'Recognition',
    awardsDesc: 'Honored by institutions that share our pursuit of design excellence.',
    contactTitle: 'Get in Touch',
    contactDesc: "Ready to bring your vision to life? We'd love to hear from you.",
    formName: 'Full Name',
    formEmail: 'Email Address',
    formMsg: 'Your Message',
    formSubmit: 'Send Message',
    guestbook: 'Guestbook',
    guestbookDesc: 'Leave your mark',
    aiTitle: 'Meridian AI',
    aiPlaceholder: 'Ask about our projects...',
    footer: '© 2024 Meridian Architecture. All rights reserved.',
    projects: [
      { num: '01', name: 'The Obsidian Tower', loc: 'Dubai, UAE', desc: 'A 72-story mixed-use tower that redefines the Dubai skyline with its faceted glass facade.' },
      { num: '02', name: 'Harbor Pavilion', loc: 'Copenhagen, Denmark', desc: 'A floating cultural center that bridges water and land, hosting exhibitions and performances.' },
      { num: '03', name: 'Solaris Residence', loc: 'Kyoto, Japan', desc: 'A luxury residential complex blending traditional Japanese aesthetics with modern sustainability.' },
      { num: '04', name: 'Nexus Campus', loc: 'Singapore', desc: 'A tech headquarters designed for collaboration, with biophilic elements throughout.' },
    ],
    team: [
      { name: 'Elena Vasquez', role: 'Founding Principal', img: 'https://images.unsplash.com/photo-1573496359142-b8d87734a5a2?w=400&h=500&fit=crop' },
      { name: 'Marcus Chen', role: 'Design Director', img: 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=400&h=500&fit=crop' },
      { name: 'Sophia Laurent', role: 'Head of Sustainability', img: 'https://images.unsplash.com/photo-1580489944761-15a19d654956?w=400&h=500&fit=crop' },
      { name: 'James Okafor', role: 'Technical Director', img: 'https://images.unsplash.com/photo-1506794778202-cad84cf45f1d?w=400&h=500&fit=crop' },
      { name: 'Yuki Tanaka', role: 'Interior Design Lead', img: 'https://images.unsplash.com/photo-1544005313-94ddf0286df2?w=400&h=500&fit=crop' },
      { name: 'David Mueller', role: 'Urban Planning', img: 'https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=400&h=500&fit=crop' },
      { name: 'Amara Osei', role: 'Project Manager', img: 'https://images.unsplash.com/photo-1531123897727-8f129e1688ce?w=400&h=500&fit=crop' },
      { name: 'Luca Rossi', role: 'Visualization Lead', img: 'https://images.unsplash.com/photo-1500648767791-00dcc994a43e?w=400&h=500&fit=crop' },
    ],
    awards: [
      { year: '2024', title: 'Pritzker Architecture Prize', org: 'The Hyatt Foundation' },
      { year: '2023', title: 'AIA Gold Medal', org: 'American Institute of Architects' },
      { year: '2023', title: 'World Architecture Festival - Building of the Year', org: 'WAF' },
      { year: '2022', title: 'RIBA International Prize', org: 'Royal Institute of British Architects' },
      { year: '2022', title: 'Aga Khan Award for Architecture', org: 'Aga Khan Development Network' },
      { year: '2021', title: 'European Prize for Architecture', org: 'European Centre' },
      { year: '2020', title: 'AIA Honor Award', org: 'American Institute of Architects' },
      { year: '2019', title: 'Mies van der Rohe Award', org: 'European Union' },
      { year: '2018', title: 'World Architecture Festival - Future Project', org: 'WAF' },
      { year: '2017', title: 'AIA Architecture Award', org: 'American Institute of Architects' },
    ],
    pubs: [
      { title: 'Meridian: Works 2008-2024', year: '2024' },
      { title: 'Light & Form', year: '2022' },
      { title: 'Sustainable Futures', year: '2021' },
      { title: 'Urban Narratives', year: '2020' },
      { title: 'Material Culture', year: '2019' },
      { title: 'The Meridian Way', year: '2018' },
    ],
  },
  zh: {
    nav: ['项目','理念','团队','荣誉','联系'],
    heroTag: '始于 2008 · 建筑与设计',
    heroTitle: '塑造地平线',
    heroSub: '我们设计超越时间的空间。光与形式交汇之处，愿景化为现实。',
    heroCta: '查看项目',
    projectsTitle: '精选项目',
    projectsDesc: '横跨三大洲的标志性作品精选。',
    philosophyTitle: '设计理念',
    philosophyText: '建筑不仅仅是建造房屋。它是创造体验、塑造社区、留下超越我们生命的遗产。我们画下的每一根线条，选择的每一种材料，都服务于比美学更宏大的目标。',
    teamTitle: '团队',
    teamDesc: '八位因共同追求卓越设计而聚在一起的远见者。',
    awardsTitle: '荣誉认可',
    awardsDesc: '与我们共同追求设计卓越的机构所给予的认可。',
    contactTitle: '联系我们',
    contactDesc: '准备好将您的愿景变为现实？我们期待您的来信。',
    formName: '姓名',
    formEmail: '邮箱',
    formMsg: '留言内容',
    formSubmit: '发送消息',
    guestbook: '留言簿',
    guestbookDesc: '留下您的印记',
    aiTitle: 'Meridian AI 助手',
    aiPlaceholder: '询问关于我们的项目...',
    footer: '© 2024 Meridian Architecture. 版权所有。',
    projects: [
      { num: '01', name: '黑曜石之塔', loc: '迪拜, 阿联酋', desc: '72层混合用途塔楼，以棱面玻璃幕墙重新定义迪拜天际线。' },
      { num: '02', name: '海港展馆', loc: '哥本哈根, 丹麦', desc: '漂浮的文化中心，连接水与陆地，举办展览和演出。' },
      { num: '03', name: '日之居', loc: '京都, 日本', desc: '融合传统日本美学与现代可持续性的豪华住宅综合体。' },
      { num: '04', name: '枢纽园区', loc: '新加坡', desc: '为协作而设计的科技总部，遍布生物亲和元素。' },
    ],
    team: [
      { name: 'Elena Vasquez', role: '创始合伙人', img: 'https://images.unsplash.com/photo-1573496359142-b8d87734a5a2?w=400&h=500&fit=crop' },
      { name: 'Marcus Chen', role: '设计总监', img: 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=400&h=500&fit=crop' },
      { name: 'Sophia Laurent', role: '可持续发展主管', img: 'https://images.unsplash.com/photo-1580489944761-15a19d654956?w=400&h=500&fit=crop' },
      { name: 'James Okafor', role: '技术总监', img: 'https://images.unsplash.com/photo-1506794778202-cad84cf45f1d?w=400&h=500&fit=crop' },
      { name: 'Yuki Tanaka', role: '室内设计主管', img: 'https://images.unsplash.com/photo-1544005313-94ddf0286df2?w=400&h=500&fit=crop' },
      { name: 'David Mueller', role: '城市规划', img: 'https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=400&h=500&fit=crop' },
      { name: 'Amara Osei', role: '项目经理', img: 'https://images.unsplash.com/photo-1531123897727-8f129e1688ce?w=400&h=500&fit=crop' },
      { name: 'Luca Rossi', role: '可视化主管', img: 'https://images.unsplash.com/photo-1500648767791-00dcc994a43e?w=400&h=500&fit=crop' },
    ],
    awards: [
      { year: '2024', title: '普利兹克建筑奖', org: '凯悦基金会' },
      { year: '2023', title: 'AIA 金奖', org: '美国建筑师协会' },
      { year: '2023', title: '世界建筑节 - 年度建筑', org: 'WAF' },
      { year: '2022', title: 'RIBA 国际奖', org: '英国皇家建筑师学会' },
      { year: '2022', title: '阿迦汗建筑奖', org: '阿迦汗发展网络' },
      { year: '2021', title: '欧洲建筑奖', org: '欧洲中心' },
      { year: '2020', title: 'AIA 荣誉奖', org: '美国建筑师协会' },
      { year: '2019', title: '密斯·凡·德·罗奖', org: '欧盟' },
      { year: '2018', title: '世界建筑节 - 未来项目', org: 'WAF' },
      { year: '2017', title: 'AIA 建筑奖', org: '美国建筑师协会' },
    ],
    pubs: [
      { title: 'Meridian: 作品集 2008-2024', year: '2024' },
      { title: '光与形式', year: '2022' },
      { title: '可持续未来', year: '2021' },
      { title: '城市叙事', year: '2020' },
      { title: '材料文化', year: '2019' },
      { title: 'Meridian 之道', year: '2018' },
    ],
  }
};

// App
function App() {
  const [lang, setLang] = useState('en');
  const [aiOpen, setAiOpen] = useState(false);
  const [scrolled, setScrolled] = useState(false);
  const t = i18n[lang];

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 50);
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  useEffect(() => {
    const observer = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) e.target.classList.add('visible'); });
    }, { threshold: 0.1 });
    document.querySelectorAll('.fade-up').forEach(el => observer.observe(el));
    return () => observer.disconnect();
  }, []);

  return (
    <div>
      {/* Nav */}
      <nav className={scrolled ? 'scrolled' : ''}>
        <div className="nav-logo">MERIDIAN</div>
        <ul className="nav-links">
          {t.nav.map((item, i) => (
            <li key={i}><a href={`#section-${i}`}>{item}</a></li>
          ))}
        </ul>
        <div className="nav-lang" onClick={() => setLang(lang === 'en' ? 'zh' : 'en')}>
          {lang === 'en' ? '中文' : 'EN'}
        </div>
      </nav>

      {/* Hero */}
      <section className="hero">
        <video className="hero-video" autoPlay muted loop playsInline poster="https://images.unsplash.com/photo-1486325212027-8081e485255e?w=1920">
          <source src="https://assets.mixkit.co/videos/preview/mixkit-city-traffic-at-night-11052-large.mp4" type="video/mp4"/>
        </video>
        <div className="hero-overlay"></div>
        <div className="hero-content">
          <div className="hero-tag">{t.heroTag}</div>
          <h1 className="hero-title">{t.heroTitle}</h1>
          <p className="hero-subtitle">{t.heroSub}</p>
          <a href="#section-0" className="hero-cta">{t.heroCta}</a>
        </div>
        <div className="scroll-indicator">SCROLL</div>
      </section>

      {/* Projects */}
      <section id="section-0">
        <div className="container">
          <div className="section-label fade-up">{t.projectsTitle}</div>
          <h2 className="section-title fade-up">{t.projectsDesc}</h2>
          <div className="projects-grid fade-up">
            {t.projects.map((p, i) => (
              <div className="project-card" key={i}>
                <img src={`https://images.unsplash.com/photo-${['1486325212027-8081e485255e','1545558014-869207e3e718','1600585154340-be6161a56a0c','1497366216548-37526070297c'][i]}?w=800&h=500&fit=crop`} alt={p.name}/>
                <div className="project-info">
                  <div className="project-num">{p.num}</div>
                  <div className="project-name">{p.name}</div>
                  <div className="project-loc">{p.loc} · {p.desc}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Philosophy */}
      <section id="section-1" className="philosophy">
        <div className="container">
          <div className="section-label fade-up">{t.philosophyTitle}</div>
          <h2 className="section-title fade-up">{t.philosophyText}</h2>
          <div className="stats-row fade-up">
            <div><div className="stat-num">148</div><div className="stat-label">Projects</div></div>
            <div><div className="stat-num">32</div><div className="stat-label">Countries</div></div>
            <div><div className="stat-num">26</div><div className="stat-label">Awards</div></div>
          </div>
        </div>
      </section>

      {/* Team */}
      <section id="section-2">
        <div className="container">
          <div className="section-label fade-up">{t.teamTitle}</div>
          <h2 className="section-title fade-up">{t.teamDesc}</h2>
          <div className="team-grid fade-up">
            {t.team.map((m, i) => (
              <div className="team-card" key={i}>
                <img src={m.img} alt={m.name} loading="lazy"/>
                <div className="team-name">{m.name}<div className="team-role">{m.role}</div></div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Awards */}
      <section id="section-3">
        <div className="container">
          <div className="section-label fade-up">{t.awardsTitle}</div>
          <h2 className="section-title fade-up">{t.awardsDesc}</h2>
          <div className="awards-timeline fade-up">
            {t.awards.map((a, i) => (
              <div className="award-item" key={i}>
                <div className="award-year">{a.year}</div>
                <div className="award-title">{a.title}</div>
                <div className="award-org">{a.org}</div>
              </div>
            ))}
          </div>
          <div className="publications fade-up">
            {t.pubs.map((p, i) => (
              <div className="pub-card" key={i}>
                <div className="pub-title">{p.title}</div>
                <div className="pub-year">{p.year}</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Contact */}
      <section id="section-4" style={{background:'var(--surface)'}}>
        <div className="container">
          <div className="section-label fade-up">{t.contactTitle}</div>
          <h2 className="section-title fade-up">{t.contactDesc}</h2>
          <div className="contact-grid fade-up">
            <div>
              <div className="form-group">
                <label className="form-label">{t.formName}</label>
                <input className="form-input" placeholder={t.formName}/>
              </div>
              <div className="form-group">
                <label className="form-label">{t.formEmail}</label>
                <input className="form-input" type="email" placeholder={t.formEmail}/>
              </div>
              <div className="form-group">
                <label className="form-label">{t.formMsg}</label>
                <textarea className="form-textarea" placeholder={t.formMsg}></textarea>
              </div>
              <button className="form-submit">{t.formSubmit}</button>
            </div>
            <div>
              <div className="guestbook">
                <h3>{t.guestbook}</h3>
                <div className="guest-entry"><div className="guest-name">Sarah Mitchell</div><div className="guest-msg">Incredible work on the Obsidian Tower. A true masterpiece of modern architecture.</div><div className="guest-date">2024-11-15</div></div>
                <div className="guest-entry"><div className="guest-name">Chen Wei</div><div className="guest-msg">Harbor Pavilion改变了我对公共空间的理解。感谢Meridian团队。</div><div className="guest-date">2024-10-28</div></div>
                <div className="guest-entry"><div className="guest-name">Marco Bianchi</div><div className="guest-msg">Visited Solaris Residence last month. The attention to detail is remarkable.</div><div className="guest-date">2024-09-12</div></div>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Footer */}
      <footer>
        <div className="container">
          <div className="footer-logo">MERIDIAN</div>
          <div className="footer-links">
            {t.nav.map((item, i) => <a key={i} href={`#section-${i}`}>{item}</a>)}
          </div>
          <div className="footer-copy">{t.footer}</div>
        </div>
      </footer>

      {/* AI Chat */}
      <button className="ai-btn" onClick={() => setAiOpen(!aiOpen)}>✦</button>
      <div className={`ai-panel ${aiOpen ? 'open' : ''}`}>
        <AIChat lang={lang} t={t} onClose={() => setAiOpen(false)}/>
      </div>
    </div>
  );
}

// AI Chat Component
function AIChat({ lang, t, onClose }) {
  const [messages, setMessages] = useState([
    { role: 'bot', text: lang === 'en' ? 'Hello! I\'m Meridian AI. Ask me about our projects, philosophy, or team.' : '你好！我是 Meridian AI。可以问我关于我们的项目、理念或团队。' }
  ]);
  const [input, setInput] = useState('');
  const msgsRef = useRef(null);

  const send = () => {
    if (!input.trim()) return;
    const userMsg = { role: 'user', text: input };
    setMessages(prev => [...prev, userMsg]);
    setInput('');
    setTimeout(() => {
      const responses = lang === 'en' ? [
        'Our flagship project, The Obsidian Tower, stands 72 stories tall in Dubai. It features a revolutionary faceted glass facade that changes appearance throughout the day.',
        'Meridian was founded in 2008 with a vision to create architecture that transcends time. We believe in the power of light, form, and material.',
        'Our team of 8 architects brings diverse perspectives from around the world. Each member contributes unique expertise to every project.',
        'We\'ve been honored with 26 international awards, including the prestigious Pritzker Prize in 2024.'
      ] : [
        '我们的旗舰项目黑曜石之塔高72层，位于迪拜。它采用革命性的棱面玻璃幕墙，日间外观不断变化。',
        'Meridian成立于2008年，愿景是创造超越时间的建筑。我们相信光、形式和材料的力量。',
        '我们的8人建筑师团队来自世界各地，每位成员为每个项目贡献独特的专业知识。',
        '我们很荣幸获得26项国际大奖，包括2024年普利兹克建筑奖。'
      ];
      setMessages(prev => [...prev, { role: 'bot', text: responses[Math.floor(Math.random() * responses.length)] }]);
    }, 800);
  };

  useEffect(() => { if (msgsRef.current) msgsRef.current.scrollTop = msgsRef.current.scrollHeight; }, [messages]);

  return (
    <>
      <div className="ai-header">
        <h4>{t.aiTitle}</h4>
        <button className="ai-close" onClick={onClose}>✕</button>
      </div>
      <div className="ai-messages" ref={msgsRef}>
        {messages.map((m, i) => <div key={i} className={`ai-msg ${m.role}`}>{m.text}</div>)}
      </div>
      <div className="ai-input-wrap">
        <input className="ai-input" value={input} onChange={e => setInput(e.target.value)} onKeyDown={e => e.key === 'Enter' && send()} placeholder={t.aiPlaceholder}/>
        <button className="ai-send" onClick={send}>→</button>
      </div>
    </>
  );
}

ReactDOM.createRoot(document.getElementById('app')).render(<App/>);
