const { useState, useEffect, useCallback } = React;

/* ─── Portfolio Data (embedded) ─── */
const PROJECTS = [
  { id:"linkou-chunhsiang", title:"林口群祥囍", type:"Residential", category:"residential", year:"2025", hashtags:["modern","minimalist"], image:"https://images.unsplash.com/photo-1600210492486-724fe5c67fb0?auto=format&fit=crop&w=600&q=80", heroImage:"https://images.unsplash.com/photo-1600210492486-724fe5c67fb0?auto=format&fit=crop&w=1200&q=80", description:"以寧靜為狀態，將現代簡約風格融入生活空間，打造溫馨住宅。" },
  { id:"xinzhuang-zhongyang", title:"新莊中央星鑽李宅", type:"Residential", category:"residential", year:"2025", hashtags:["luxury","interior"], image:"https://images.unsplash.com/photo-1600607687939-ce8a6c25118c?auto=format&fit=crop&w=600&q=80", heroImage:"https://images.unsplash.com/photo-1600607687939-ce8a6c25118c?auto=format&fit=crop&w=1200&q=80", description:"精緻且奢華的設計語彙，帶來全新的居住體驗。" },
  { id:"daan-shida", title:"大安師大職員宿鄭宅", type:"Residential", category:"residential", year:"2025", hashtags:["classic","design"], image:"https://images.unsplash.com/photo-1598928506311-c55dd5802c27?auto=format&fit=crop&w=600&q=80", heroImage:"https://images.unsplash.com/photo-1598928506311-c55dd5802c27?auto=format&fit=crop&w=1200&q=80", description:"結合經典元素與現代設計，展現獨特的文化底蘊。" },
  { id:"dadu-taiping", title:"大肚太平路林宅", type:"Residential", category:"residential", year:"2025", hashtags:["modern","spacious"], image:"https://images.unsplash.com/photo-1600566753190-17f0baa2a6c3?auto=format&fit=crop&w=600&q=80", heroImage:"https://images.unsplash.com/photo-1600566753190-17f0baa2a6c3?auto=format&fit=crop&w=1200&q=80", description:"寬敞明亮的空間規劃，充滿生機與活力。" },
  { id:"yongkang-shuiwu", title:"永康水舞紀潘宅", type:"Residential", category:"residential", year:"2025", hashtags:["elegant","comfortable"], image:"https://images.unsplash.com/photo-1600585154340-be6161a56a0c?auto=format&fit=crop&w=600&q=80", heroImage:"https://images.unsplash.com/photo-1600585154340-be6161a56a0c?auto=format&fit=crop&w=1200&q=80", description:"優雅而舒適的居住氛圍，提供放鬆的避風港。" },
  { id:"annan-cixing", title:"安南慈興五街林宅", type:"Residential", category:"residential", year:"2025", hashtags:["minimalist","bright"], image:"https://images.unsplash.com/photo-1512917774080-9991f1c4c750?auto=format&fit=crop&w=600&q=80", heroImage:"https://images.unsplash.com/photo-1512917774080-9991f1c4c750?auto=format&fit=crop&w=1200&q=80", description:"極簡主義與自然光線的完美結合。" },
  { id:"nanzi-dahe", title:"楠梓大河樣周宅", type:"Residential", category:"multilayer", year:"2025", hashtags:["contemporary","stylish"], image:"https://images.unsplash.com/photo-1502005229762-cf1b2da7c5d6?auto=format&fit=crop&w=600&q=80", heroImage:"https://images.unsplash.com/photo-1502005229762-cf1b2da7c5d6?auto=format&fit=crop&w=1200&q=80", description:"充滿現代感與時尚氣息的品味生活。" },
  { id:"nanzi-daxue", title:"楠梓大學五十八街莊宅", type:"Residential", category:"multilayer", year:"2025", hashtags:["chic","cozy"], image:"https://images.unsplash.com/photo-1593696140826-c58b021acf8b?auto=format&fit=crop&w=600&q=80", heroImage:"https://images.unsplash.com/photo-1593696140826-c58b021acf8b?auto=format&fit=crop&w=1200&q=80", description:"別緻且溫馨的透天設計。" },
  { id:"nanzi-baida", title:"楠梓百達悠悅蘇宅", type:"Residential", category:"residential", year:"2025", hashtags:["serene","peaceful"], image:"https://images.unsplash.com/photo-1588854337236-6889d631faa8?auto=format&fit=crop&w=600&q=80", heroImage:"https://images.unsplash.com/photo-1588854337236-6889d631faa8?auto=format&fit=crop&w=1200&q=80", description:"寧靜祥和的居住環境，讓心靈徹底放鬆。" }
];

/* ─── Simple Hash Router ─── */
function useHashRouter() {
  const [route, setRoute] = useState(window.location.hash || '#/');
  useEffect(() => {
    const handler = () => setRoute(window.location.hash || '#/');
    window.addEventListener('hashchange', handler);
    return () => window.removeEventListener('hashchange', handler);
  }, []);
  return route;
}
function navigate(hash) { window.location.hash = hash; window.scrollTo(0, 0); }

/* ─── Opening Animation ─── */
function OpeningMask({ onDone }) {
  const [phase, setPhase] = useState('text-in');
  useEffect(() => {
    document.body.classList.add('no-scroll');
    const t1 = setTimeout(() => setPhase('text-out'), 2000);
    const t2 = setTimeout(() => setPhase('slide-up'), 2600);
    const t3 = setTimeout(() => { setPhase('done'); document.body.classList.remove('no-scroll'); onDone(); }, 3600);
    return () => { clearTimeout(t1); clearTimeout(t2); clearTimeout(t3); document.body.classList.remove('no-scroll'); };
  }, []);
  if (phase === 'done') return null;
  return (
    <div className={`opening-mask phase-${phase}`}>
      <h1 className="opening-text">眷顧設計 | Tranquil Design</h1>
    </div>
  );
}

/* ─── Stagger wrapper ─── */
function StaggerIn({ children, active, delay = 0 }) {
  const [vis, setVis] = useState(false);
  useEffect(() => { if (active) { const t = setTimeout(() => setVis(true), delay); return () => clearTimeout(t); } }, [active]);
  return <div className={`stagger-item ${vis ? 'visible' : ''}`} style={vis ? { animationDelay: `${delay}ms` } : {}}>{children}</div>;
}

/* ─── Navbar ─── */
function Header({ currentRoute }) {
  const [open, setOpen] = useState(false);
  const links = [
    { title:"關於眷顧", sub:"About", href:"#/about" },
    { title:"作品集", sub:"PORTFOLIO", href:"#/portfolio" },
    { title:"服務流程", sub:"SERVICES", href:"#/services" },
    { title:"裝修知識", sub:"KNOWLEDGE", href:"#/knowledge" },
    { title:"電子書", sub:"E-BOOK", href:"#/ebook" },
    { title:"聯絡我們", sub:"CONTACT", href:"#/contact" }
  ];
  return (
    <header className="header">
      <div className="header-inner">
        <div className="header-logo" onClick={() => navigate('#/')}>
          <img src="/public/logo.svg" alt="眷顧設計" />
        </div>
        <div className="nav-toggle" onClick={() => setOpen(!open)}>
          <span /><span /><span />
        </div>
        <nav className={`nav-links ${open ? 'open' : ''}`}>
          {links.map((l, i) => (
            <a key={i} className={`nav-item ${currentRoute === l.href ? 'active' : ''}`}
               href={l.href} onClick={() => setOpen(false)}>
              <span className="nav-subtitle">{l.sub}</span>
              <span className="nav-title">{l.title}</span>
            </a>
          ))}
        </nav>
      </div>
    </header>
  );
}

/* ─── Footer ─── */
function Footer() {
  const [branch, setBranch] = useState('taipei');
  return (
    <footer className="footer" id="contact">
      <div className="footer-inner">
        <div className="footer-top">
          <div>
            <div className="footer-logo-area">
              <img className="footer-logo" src="/public/logo.svg" alt="眷顧設計" />
              <button className="btn-consult">立即諮詢</button>
            </div>
            <div className="footer-contact" style={{marginTop:'1rem'}}>
              <p>服務時間：09:00 - 18:00</p>
              <p>聯絡電話：00-000-0000</p>
              <p>電子信箱：xxx@gmail.com</p>
            </div>
          </div>
          <div className="footer-branches">
            <div className="branch-tabs">
              <button className={`branch-tab ${branch==='taipei'?'active':''}`} onClick={()=>setBranch('taipei')}>台北分部</button>
              <button className={`branch-tab ${branch==='kaohsiung'?'active':''}`} onClick={()=>setBranch('kaohsiung')}>高雄分部</button>
            </div>
            <p className="branch-address">地址：{branch==='taipei'?'台北市信義區...':'高雄市前金區...'}</p>
          </div>
        </div>
        <div className="footer-bottom">
          <div className="social-links">
            <div className="social-icon">LN</div>
            <div className="social-icon">FB</div>
            <div className="social-icon">IG</div>
          </div>
          <p className="copyright">Copyright © 眷顧設計</p>
        </div>
      </div>
    </footer>
  );
}

/* ─── Portfolio Card ─── */
function PortfolioCard({ project, showHashtags }) {
  return (
    <div className="portfolio-card" onClick={() => navigate('#/project/' + project.id)}>
      <div className="portfolio-card-image"><img src={project.image} alt={project.title} /></div>
      <div className="portfolio-card-info">
        <div>
          <div className="portfolio-card-title">{project.title}</div>
          <div className="portfolio-card-meta">{project.type} • {project.year}</div>
          {showHashtags && <div className="portfolio-card-hashtags">{project.hashtags.map(t => '#'+t).join(' • ')}</div>}
        </div>
        <span className="portfolio-card-arrow">↗</span>
      </div>
    </div>
  );
}

/* ─── Process Steps ─── */
function ProcessSteps({ steps }) {
  return (
    <div className="process-steps">
      {steps.map((s, i) => (
        <div className="process-step" key={i}>
          <span className="process-step-num">0{i+1}</span>
          <div className="process-step-line" />
          <div className="process-step-circle" />
          <span className="process-step-label">{s}</span>
        </div>
      ))}
    </div>
  );
}

/* ═══════════════════════════════════════
   PAGES
   ═══════════════════════════════════════ */

function HomePage({ ready }) {
  return (
    <div>
      <StaggerIn active={ready} delay={0}>
        <section className="hero-section">
          <div className="hero-bg" style={{backgroundImage:"url('https://images.unsplash.com/photo-1600210492486-724fe5c67fb0?auto=format&fit=crop&w=1920&q=80')"}} />
          <div className="hero-overlay" />
          <div className="hero-content">
            <h1 className="hero-title">FURNITURE &<br/>DESIGN SERVICES</h1>
          </div>
        </section>
      </StaggerIn>

      <StaggerIn active={ready} delay={200}>
        <section className="portfolio-home">
          <div className="portfolio-header">
            <div className="section-header">
              <div className="section-label">Portfolio</div>
              <h2 className="section-title">精選作品</h2>
            </div>
            <button className="btn-view-all" onClick={() => navigate('#/portfolio')}>View All Works</button>
          </div>
          <div className="portfolio-grid portfolio-grid-3">
            {PROJECTS.slice(0, 3).map(p => <PortfolioCard key={p.id} project={p} />)}
          </div>
          <div className="portfolio-grid portfolio-grid-2">
            {PROJECTS.slice(3, 5).map(p => <PortfolioCard key={p.id} project={p} />)}
          </div>
        </section>
      </StaggerIn>

      <StaggerIn active={ready} delay={400}>
        <section className="services-section">
          <div className="container">
            <div className="section-header centered">
              <div className="section-label">Our Process</div>
              <h2 className="section-title">服務流程</h2>
            </div>
            <ProcessSteps steps={["初步諮詢","現場丈量","平配提案","設計合約","工程報價","完工交屋"]} />
          </div>
        </section>
      </StaggerIn>
    </div>
  );
}

function AboutPage() {
  const team = [
    {role:"設計總監 Design Director", name:"ＯＯＯ"},
    {role:"資深設計師 Designer", name:"ＯＯＯ"},
    {role:"助理設計師 Designer Assistant", name:"ＯＯＯ"}
  ];
  return (
    <div className="about-page">
      <div className="about-brand">
        <h1 className="about-brand-title">眷顧設計｜品牌理念</h1>
        <p className="about-brand-philosophy">以寧靜為狀態 (Tranquil)，以眷顧為設計的起點；空間，讓人安放而不是被填滿。</p>
        <p className="about-brand-en">Tranquil Design, Designing Your Tranquility.</p>
      </div>
      <div className="about-team">
        <div className="section-header">
          <div className="section-label">Team Members</div>
          <h2 className="section-title">團隊成員</h2>
        </div>
        <div className="about-team-grid">
          <div className="team-photo" />
          <div className="team-members">
            {team.map((m, i) => (
              <div className="team-member" key={i}>
                <div><div className="team-member-role">{m.role}</div><div className="team-member-name">{m.name}</div></div>
                <div><div className="team-member-role">{m.role}</div><div className="team-member-name">{m.name}</div></div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

function PortfolioPage() {
  const [filter, setFilter] = useState('all');
  const cats = [
    {key:'residential', en:'Residential', zh:'住宅空間'},
    {key:'commercial', en:'Commercial', zh:'商業空間'},
    {key:'multilayer', en:'Multilayer', zh:'複層住宅 / 透天別墅'},
    {key:'all', en:'All Projects', zh:'所有作品'}
  ];
  const filtered = filter === 'all' ? PROJECTS : PROJECTS.filter(p => p.category === filter);
  return (
    <div className="portfolio-page">
      <div className="container" style={{paddingTop:'3rem'}}>
        <div className="portfolio-filters">
          {cats.map(c => (
            <button key={c.key} className={`filter-btn ${filter===c.key?'active':''}`} onClick={() => setFilter(c.key)}>
              <span className="filter-en">{c.en}</span>
              <span className="filter-zh">{c.zh}</span>
            </button>
          ))}
        </div>
        <div className="portfolio-list-grid">
          {filtered.map(p => <PortfolioCard key={p.id} project={p} showHashtags />)}
        </div>
      </div>
    </div>
  );
}

function ProjectDetailPage({ id }) {
  const project = PROJECTS.find(p => p.id === id);
  if (!project) return <div className="placeholder-page"><h2 className="section-title">找不到此作品</h2></div>;
  return (
    <div className="project-detail">
      <div className="project-detail-inner">
        <div className="project-sidebar">
          <div className="project-back" onClick={() => navigate('#/portfolio')}>
            <span className="project-back-icon">‹</span>
          </div>
          <div className="project-meta-type">{project.type} • {project.year}</div>
          <h1 className="project-meta-title">{project.title}</h1>
          <p className="project-meta-desc">{project.description}</p>
          <p className="project-meta-tags">{project.hashtags.map(t => '#'+t).join(' ')}</p>
        </div>
        <div className="project-images">
          <img className="project-hero-img" src={project.heroImage} alt={project.title} />
          <img className="project-hero-img" src={project.image} alt={project.title} style={{objectPosition:'top'}} />
          <div className="project-gallery-row">
            <img src={project.heroImage} alt="" style={{objectPosition:'center'}} />
            <img src={project.image} alt="" style={{objectPosition:'bottom'}} />
          </div>
        </div>
      </div>
    </div>
  );
}

function ServicesPage() {
  const sSteps = ["初步諮詢","現場丈量","平配提案","設計合約","工程報價","完工交屋"];
  const eSteps = ["保護工程","拆除工程","水電工程","泥作工程","木作工程","油漆收尾"];
  return (
    <div style={{paddingTop:'75px'}}>
      <section className="services-section">
        <div className="container">
          <div className="section-header centered"><div className="section-label">Service Process</div><h2 className="section-title">服務流程</h2></div>
          <ProcessSteps steps={sSteps} />
        </div>
      </section>
      <section className="services-section" style={{background:'var(--color-bg-light)'}}>
        <div className="container">
          <div className="section-header centered"><div className="section-label">Engineering Process</div><h2 className="section-title">工程流程</h2></div>
          <ProcessSteps steps={eSteps} />
        </div>
      </section>
    </div>
  );
}

function PlaceholderPage({ label, title }) {
  return (
    <div className="placeholder-page">
      <div className="section-label">{label}</div>
      <h2 className="section-title">{title}</h2>
      <p style={{marginTop:'1rem'}}>Coming Soon — 敬請期待</p>
    </div>
  );
}

/* ═══════════════════════════════════════
   APP ROOT
   ═══════════════════════════════════════ */

function App() {
  const [maskDone, setMaskDone] = useState(false);
  const route = useHashRouter();

  const renderPage = () => {
    if (route === '#/' || route === '' || route === '#') return <HomePage ready={maskDone} />;
    if (route === '#/about') return <AboutPage />;
    if (route === '#/portfolio') return <PortfolioPage />;
    if (route.startsWith('#/project/')) return <ProjectDetailPage id={route.replace('#/project/','')} />;
    if (route === '#/services') return <ServicesPage />;
    if (route === '#/knowledge') return <PlaceholderPage label="Knowledge" title="裝修知識" />;
    if (route === '#/ebook') return <PlaceholderPage label="E-Book" title="電子書" />;
    if (route === '#/contact') { setTimeout(() => document.getElementById('contact')?.scrollIntoView({behavior:'smooth'}), 100); return <HomePage ready={true} />; }
    return <HomePage ready={true} />;
  };

  return (
    <div>
      <OpeningMask onDone={() => setMaskDone(true)} />
      <StaggerIn active={maskDone} delay={0}>
        <Header currentRoute={route} />
      </StaggerIn>
      {renderPage()}
      <StaggerIn active={maskDone || route !== '#/'} delay={600}>
        <Footer />
      </StaggerIn>
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
