const { useEffect, useRef, useState } = React;
const mountRoot =
  typeof ReactDOM.createRoot === 'function'
    ? ReactDOM.createRoot(document.getElementById('root'))
    : {
        render(element) {
          ReactDOM.render(element, document.getElementById('root'));
        }
      };

const defaultData = {
  settings: {
    company_name: 'Atelier Struktur',
    hero_badge: 'Konstruksi bangunan modern',
    hero_title_line_1: 'Bangun ruang',
    hero_title_line_2: 'yang terasa presisi.',
    hero_description:
      'Dari rumah tinggal sampai proyek komersial, kami merancang, membangun, dan merapikan detail agar hasilnya kuat, efisien, dan enak dipandang.',
    hero_primary_cta_label: 'Mulai konsultasi',
    hero_primary_cta_url: '#kontak',
    hero_secondary_cta_label: 'Lihat proyek',
    hero_secondary_cta_url: '#proyek',
    about_title: 'Struktur rapi, progres jelas, hasil terasa mahal.',
    about_description:
      'Kami menyatukan perencanaan teknis, kontrol lapangan, dan ritme eksekusi yang disiplin. Fokusnya sederhana: bangunan harus kokoh, timeline terkendali, dan kualitas akhir tetap bersih hingga serah terima.',
    contact_phone: '+62 812 0000 0000',
    contact_email: 'halo@atelierstruktur.com',
    contact_address: 'Makassar, Sulawesi Selatan',
    cta_title: 'Punya lahan atau proyek yang siap dimulai?',
    cta_description:
      'Kirim kebutuhan Anda, lalu kami bantu mapping konsep, estimasi, dan tahapan pembangunan yang paling realistis.',
    footer_note: 'Membangun dengan disiplin, detail, dan komunikasi yang enak diajak kerja.'
  },
  stats: [
    { id: 1, value_label: '120+', label: 'proyek selesai tepat target', sort_order: 1 },
    { id: 2, value_label: '14', label: 'tahun pengalaman tim inti', sort_order: 2 },
    { id: 3, value_label: '98%', label: 'retensi klien dan referral', sort_order: 3 },
    { id: 4, value_label: '24/7', label: 'monitoring progres lapangan', sort_order: 4 }
  ],
  services: [
    {
      id: 1,
      title: 'Desain & build',
      description: 'Satu alur dari konsep, gambar kerja, anggaran, sampai eksekusi lapangan.',
      icon: 'DB',
      sort_order: 1
    },
    {
      id: 2,
      title: 'Konstruksi komersial',
      description: 'Ruko, kantor, showroom, dan ruang usaha dengan ritme kerja yang tertata.',
      icon: 'CM',
      sort_order: 2
    },
    {
      id: 3,
      title: 'Renovasi struktural',
      description: 'Upgrade tampilan dan kekuatan bangunan lama tanpa kehilangan efisiensi biaya.',
      icon: 'RV',
      sort_order: 3
    }
  ],
  projects: [
    {
      id: 1,
      title: 'Residensi Karebosi',
      category: 'Hunian premium',
      location: 'Makassar',
      year_label: '2025',
      size_label: '780 m2',
      summary: 'Hunian tiga lantai dengan struktur bersih, bukaan lebar, dan pengerjaan interior terkontrol.',
      image_url:
        'https://images.unsplash.com/photo-1511818966892-d7d671e672a2?auto=format&fit=crop&w=1400&q=80',
      accent_color: '#d38841',
      is_featured: 1,
      sort_order: 1
    },
    {
      id: 2,
      title: 'Ruang Niaga Panakkukang',
      category: 'Komersial',
      location: 'Makassar',
      year_label: '2024',
      size_label: '1.240 m2',
      summary: 'Showroom dan kantor operasional dengan fasad tegas dan alur pengunjung yang efisien.',
      image_url:
        'https://images.unsplash.com/photo-1486406146926-c627a92ad1ab?auto=format&fit=crop&w=1400&q=80',
      accent_color: '#bf6d2f',
      is_featured: 1,
      sort_order: 2
    },
    {
      id: 3,
      title: 'Villa Tebing Selatan',
      category: 'Hospitality',
      location: 'Maros',
      year_label: '2026',
      size_label: '960 m2',
      summary: 'Konstruksi vila lanskap dengan detailing batu, beton ekspos, dan area publik yang dramatis.',
      image_url:
        'https://images.unsplash.com/photo-1460317442991-0ec209397118?auto=format&fit=crop&w=1400&q=80',
      accent_color: '#ad5f28',
      is_featured: 1,
      sort_order: 3
    }
  ]
};

const processSteps = [
  {
    index: '01',
    title: 'Kebutuhan dipetakan',
    description: 'Kami bedah target ruang, budget, dan timeline supaya keputusan awal tetap realistis.'
  },
  {
    index: '02',
    title: 'Eksekusi dikunci rapi',
    description: 'Gambar kerja, jadwal, material, dan kontrol lapangan disusun agar progres selalu terukur.'
  },
  {
    index: '03',
    title: 'Serah terima percaya diri',
    description: 'Finishing dirapikan, punch list diselesaikan, lalu bangunan siap dipakai tanpa drama.'
  }
];

function normalizePayload(payload) {
  return {
    settings: { ...defaultData.settings, ...(payload?.settings ?? {}) },
    stats: Array.isArray(payload?.stats) && payload.stats.length ? payload.stats : defaultData.stats,
    services:
      Array.isArray(payload?.services) && payload.services.length ? payload.services : defaultData.services,
    projects:
      Array.isArray(payload?.projects) && payload.projects.length ? payload.projects : defaultData.projects
  };
}

function useReveal() {
  const ref = useRef(null);
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    if (!ref.current) {
      return undefined;
    }

    const observer = new IntersectionObserver(
      (entries) => {
        if (entries.some((entry) => entry.isIntersecting)) {
          setVisible(true);
          observer.disconnect();
        }
      },
      { threshold: 0.18 }
    );

    observer.observe(ref.current);
    return () => observer.disconnect();
  }, []);

  return [ref, visible];
}

function Reveal({ children }) {
  const [ref, visible] = useReveal();
  return (
    <div ref={ref} className={`reveal${visible ? ' is-visible' : ''}`}>
      {children}
    </div>
  );
}

function Header({ settings }) {
  return (
    <header className="topbar">
      <div className="page-wrap topbar-inner">
        <a href="#home" className="brand">
          <span className="brand-mark">AS</span>
          <span className="brand-copy">
            <strong>{settings.company_name}</strong>
            <span>Design, build, supervise</span>
          </span>
        </a>
        <nav className="nav" aria-label="Navigasi utama">
          <a href="#layanan">Layanan</a>
          <a href="#proyek">Proyek</a>
          <a href="#proses">Proses</a>
          <a href="#kontak">Kontak</a>
          <a className="nav-cta" href="admin/">
            Admin
          </a>
        </nav>
      </div>
    </header>
  );
}

function Hero({ settings, stats, loading }) {
  const primaryUrl = settings.hero_primary_cta_url || '#kontak';
  const secondaryUrl = settings.hero_secondary_cta_url || '#proyek';

  return (
    <section className="hero" id="home">
      <div className="page-wrap">
        <div className="hero-panel">
          <div className="hero-grid">
            <Reveal>
              <div className="hero-copy">
                <span className="eyebrow">{settings.hero_badge}</span>
                <h1>
                  {settings.hero_title_line_1}
                  <br />
                  {settings.hero_title_line_2}
                </h1>
                <p>{settings.hero_description}</p>
                <div className="hero-actions">
                  <a className="button button-primary" href={primaryUrl}>
                    {settings.hero_primary_cta_label}
                  </a>
                  <a className="button button-secondary" href={secondaryUrl}>
                    {settings.hero_secondary_cta_label}
                  </a>
                </div>
                {loading ? <div className="loading-ribbon">Memuat konten terbaru...</div> : null}
              </div>
            </Reveal>

            <Reveal>
              <aside className="hero-aside">
                <article className="spotlight-card">
                  <small>Featured build</small>
                  <strong>Tim lapangan yang rapi, progres yang selalu terbaca.</strong>
                  <span>Untuk proyek hunian, komersial, renovasi, dan bangunan custom.</span>
                </article>
                <div className="mini-card-grid">
                  {stats.slice(0, 2).map((item) => (
                    <article className="mini-card" key={item.id}>
                      <strong>{item.value_label}</strong>
                      <span>{item.label}</span>
                    </article>
                  ))}
                </div>
              </aside>
            </Reveal>
          </div>
        </div>
      </div>
    </section>
  );
}

function SectionHeading({ title, description }) {
  return (
    <div className="section-heading">
      <h2>{title}</h2>
      <p>{description}</p>
    </div>
  );
}

function StatsSection({ stats }) {
  return (
    <section className="section">
      <div className="page-wrap">
        <Reveal>
          <div className="stats-grid">
            {stats.map((item) => (
              <article className="stat-card" key={item.id}>
                <strong>{item.value_label}</strong>
                <span>{item.label}</span>
              </article>
            ))}
          </div>
        </Reveal>
      </div>
    </section>
  );
}

function ServicesSection({ services }) {
  return (
    <section className="section" id="layanan">
      <div className="page-wrap">
        <Reveal>
          <SectionHeading
            title="Jasa utama"
            description="Layanan kami dirancang ringkas: jelas di awal, disiplin saat eksekusi, dan tetap fleksibel saat proyek berkembang."
          />
        </Reveal>
        <div className="services-grid">
          {services.map((service) => (
            <Reveal key={service.id}>
              <article className="service-card">
                <span className="service-tag">{service.icon || 'AS'}</span>
                <h3>{service.title}</h3>
                <p>{service.description}</p>
              </article>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

function ProjectsSection({ projects }) {
  return (
    <section className="section" id="proyek">
      <div className="page-wrap">
        <Reveal>
          <SectionHeading
            title="Proyek terpilih"
            description="Beberapa proyek yang menunjukkan cara kami menjaga struktur, material, dan detail akhir tetap terasa premium."
          />
        </Reveal>
        <div className="projects-stack">
          {projects.map((project) => (
            <Reveal key={project.id}>
              <article className="project-card">
                <div className="project-image" style={{ backgroundImage: `url(${project.image_url})` }} />
                <div className="project-overlay" />
                <div className="project-copy">
                  <small>{project.category}</small>
                  <h3>{project.title}</h3>
                  <p>{project.summary}</p>
                  <div className="project-meta">
                    <span>{project.location}</span>
                    <span>{project.year_label}</span>
                    <span>{project.size_label}</span>
                  </div>
                </div>
              </article>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

function AboutSection({ settings }) {
  return (
    <section className="section" id="proses">
      <div className="page-wrap">
        <div className="about-layout">
          <Reveal>
            <div className="about-panel">
              <SectionHeading title={settings.about_title} description={settings.about_description} />
            </div>
          </Reveal>
          <div className="process-grid">
            {processSteps.map((step) => (
              <Reveal key={step.index}>
                <article className="process-card">
                  <span className="process-index">{step.index}</span>
                  <h3>{step.title}</h3>
                  <p>{step.description}</p>
                </article>
              </Reveal>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

function CtaSection({ settings }) {
  return (
    <section className="cta" id="kontak">
      <div className="page-wrap">
        <Reveal>
          <div className="cta-card">
            <div>
              <h2>{settings.cta_title}</h2>
              <p>{settings.cta_description}</p>
            </div>
            <div className="hero-actions">
              <a className="button button-primary" href={`mailto:${settings.contact_email}`}>
                {settings.contact_email}
              </a>
              <a className="button button-secondary" href={`tel:${settings.contact_phone.replace(/\s+/g, '')}`}>
                {settings.contact_phone}
              </a>
            </div>
          </div>
        </Reveal>
      </div>
    </section>
  );
}

function Footer({ settings }) {
  return (
    <footer className="footer">
      <div className="page-wrap footer-inner">
        <span>{settings.company_name}</span>
        <span>{settings.contact_address}</span>
        <span>{settings.footer_note}</span>
      </div>
    </footer>
  );
}

function App() {
  const [data, setData] = useState(defaultData);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let active = true;

    fetch('api/content.php', {
      headers: {
        Accept: 'application/json'
      }
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error('Failed to load content');
        }
        return response.json();
      })
      .then((payload) => {
        if (active) {
          setData(normalizePayload(payload));
        }
      })
      .catch(() => {
        if (active) {
          setData(defaultData);
        }
      })
      .finally(() => {
        if (active) {
          setLoading(false);
        }
      });

    return () => {
      active = false;
    };
  }, []);

  return (
    <div className="site-shell">
      <Header settings={data.settings} />
      <main>
        <Hero settings={data.settings} stats={data.stats} loading={loading} />
        <StatsSection stats={data.stats} />
        <ServicesSection services={data.services} />
        <ProjectsSection projects={data.projects} />
        <AboutSection settings={data.settings} />
        <CtaSection settings={data.settings} />
      </main>
      <Footer settings={data.settings} />
    </div>
  );
}

mountRoot.render(<App />);
