﻿/* global React, LogoMark, LogoWordmark,
   Button, MonoLabel, StatusPill,
   ProjectCard, ProjectCardEmpty, ServiceCard, SupportCard, LabCard,
   SocialGrid, SectionHead, SocialIcon */

// ------------------------------------------------------------
// PROJECT MEDIA ALBUM
// ------------------------------------------------------------
function ProjectMediaAlbum({ project, compact = false }) {
  const heroMedia = {
    image: project.image,
    alt: project.imageAlt || project.title,
    caption: project.imageCaption || 'project image',
  };
  const initialGalleryItems = (project.gallery || []).filter(item => item && item.image);
  const visibleGalleryItems = initialGalleryItems.slice(0, 4);
  const queuedGalleryItems = initialGalleryItems.slice(4);
  const [selectedMedia, setSelectedMedia] = React.useState(heroMedia);
  const [galleryItems, setGalleryItems] = React.useState(visibleGalleryItems);
  const [queuedItems, setQueuedItems] = React.useState(queuedGalleryItems);

  React.useEffect(() => {
    setSelectedMedia(heroMedia);
    setGalleryItems(visibleGalleryItems);
    setQueuedItems(queuedGalleryItems);
  }, [project.id]);

  function swapGalleryImage(index) {
    const nextMedia = galleryItems[index];
    if (!nextMedia) return;
    const replacementMedia = queuedItems[0] || selectedMedia;
    const nextQueue = queuedItems.length > 0
      ? [...queuedItems.slice(1), selectedMedia]
      : queuedItems;
    setGalleryItems(items => items.map((item, i) => (i === index ? replacementMedia : item)));
    setQueuedItems(nextQueue);
    setSelectedMedia(nextMedia);
  }

  return (
    <div className={'xs-pd-media ' + (compact ? 'is-compact' : '')} aria-label="Project image gallery">
      <div className={'xs-pd-hero ' + (selectedMedia.image ? 'has-image' : '')}>
        {selectedMedia.image && <img className="xs-media-img" src={selectedMedia.image} alt={selectedMedia.alt || selectedMedia.caption || project.title} loading={compact ? 'lazy' : undefined} />}
        <div className="xs-pd-hero-overlay">
          <MonoLabel prefix="">{selectedMedia.caption || 'project image'}</MonoLabel>
        </div>
      </div>

      <div className="xs-pd-media-rail" aria-label="Choose project image">
        {galleryItems.map((item, i) => (
          <button
            type="button"
            className="xs-pd-rail-thumb"
            key={`${item.image}-${i}`}
            onClick={() => swapGalleryImage(i)}
            aria-label={`View ${item.caption || `${project.title} image ${i + 1}`}`}
          >
            <img src={item.image} alt="" loading="lazy" />
            {item.caption && <span>{item.caption}</span>}
          </button>
        ))}
      </div>
    </div>
  );
}

// ------------------------------------------------------------
// HOME
// ------------------------------------------------------------
function HomePage({ onNav, onOpenProject }) {
  const D = window.XILROS_DATA;
  const featured = D.projects[0];

  return (
    <main className="xs-main">

      {/* hero */}
      <section className="xs-hero">
        <div className="xs-hero-inner">
          <div className="xs-hero-text">
            <h1 className="xs-hero-h1">Mechatronics<br/>Engineering Studio.</h1>
            <p className="xs-hero-lead">
              Robotics, embedded systems, 3D printed mechanisms, and practical prototype development.
            </p>
            <p className="xs-hero-body">
              XILROS builds practical mechatronic systems, from mechanical concepts and electronics integration to firmware, testing, and documentation.
            </p>
            <div className="xs-hero-cta">
              <Button variant="primary" onClick={() => onNav('projects')}>View Projects</Button>
              <Button variant="secondary" href={(window.XILROS_DATA.support || {}).url || '#'}>Support the Lab</Button>
            </div>
          </div>
          <div className="xs-hero-mark" aria-hidden="true">
            <LogoMark size={260} color="var(--color-logo-on-dark)" bg="var(--color-canvas-dark)" />
          </div>
        </div>
      </section>

      {/* featured project */}
      <section className="xs-section">
        <SectionHead
          eyebrow="featured project - 01"
          title={featured.title}
          kicker={featured.summary}
          action={<Button variant="secondary" size="sm" onClick={() => onOpenProject(featured.id)}>View Project -></Button>}
        />
        <div className="xs-feat">
          <ProjectMediaAlbum project={featured} compact />
          <div className="xs-feat-side">
            <div className="xs-feat-row">
              <span className="xs-mono">category</span>
              <span>{featured.category}</span>
            </div>
            <div className="xs-feat-row">
              <span className="xs-mono">status</span>
              <StatusPill>{featured.status}</StatusPill>
            </div>
            <div className="xs-feat-row">
              <span className="xs-mono">tags</span>
              <span className="xs-tags">
                {featured.tags.map(t => <span key={t} className="xs-tag">{t}</span>)}
              </span>
            </div>
            <div className="xs-feat-row">
              <span className="xs-mono">next</span>
              <span>{featured.status_detail.next}</span>
            </div>
            <Button variant="ghost" onClick={() => onOpenProject(featured.id)}>Read project notes -></Button>
          </div>
        </div>
      </section>

      {/* services */}
      <section className="xs-section">
        <SectionHead
          eyebrow="services"
          title="What XILROS does"
          kicker="Selected practice areas for practical mechatronics, prototyping, and technical development."
        />
        <div className="xs-services">
          {D.services.map((s, i) => (
            <ServiceCard key={s.id} idx={i} title={s.title} desc={s.desc} />
          ))}
        </div>
      </section>

      {/* lab teaser */}
      <section className="xs-section">
        <SectionHead
          eyebrow="lab"
          title="Recent from the Lab"
          kicker="Short updates from active builds, project releases, and technical experiments."
          action={<Button variant="secondary" size="sm" onClick={() => onNav('lab')}>See all -></Button>}
        />
        <div className="xs-lab-grid">
          {D.lab.slice(0, 3).map(e => <LabCard key={e.id} entry={e} homePreview />)}
        </div>
      </section>

      {/* socials */}
      <section className="xs-section">
        <SectionHead
          eyebrow="channels"
          title="Follow the build"
          kicker="Projects, build logs and tests are posted in short form on these channels first."
        />
        <SocialGrid socials={D.socials} />
      </section>

      {/* final CTA */}
      <section className="xs-section">
        <div className="xs-finalcta">
          <div className="xs-finalcta-text">
            <MonoLabel color="var(--color-primary-on-dark)">get in touch</MonoLabel>
            <h2 className="xs-finalcta-h">Have a project, collaboration idea,<br/>or technical question?</h2>
            <p className="xs-finalcta-p">Open to project work, brand collaborations, and technical conversations.</p>
          </div>
          <div className="xs-finalcta-cta">
            <Button variant="primary" onClick={() => onNav('contact')}>Contact</Button>
            <Button variant="secondary" onClick={() => onNav('projects')}>View Projects</Button>
          </div>
        </div>
      </section>
    </main>
  );
}

// ------------------------------------------------------------
// PROJECTS INDEX
// ------------------------------------------------------------
function ProjectsPage({ onOpenProject }) {
  const D = window.XILROS_DATA;
  return (
    <main className="xs-main">
      <section className="xs-section is-top">
        <SectionHead
          eyebrow="projects"
          title="Selected work."
          kicker="One active project. More land here as they reach a documented state."
        />
        <div className="xs-project-grid">
          {D.projects.map(p => <ProjectCard key={p.id} p={p} onOpen={onOpenProject} />)}
          <ProjectCardEmpty />
          <ProjectCardEmpty headline="Have a build in mind?" sub="Reach out via the contact page - open to collaborations." />
        </div>
      </section>
    </main>
  );
}

// ------------------------------------------------------------
// PROJECT DETAIL
// ------------------------------------------------------------
function ProjectDetailPage({ projectId, onNav }) {
  const D = window.XILROS_DATA;
  const p = D.projects.find(x => x.id === projectId || x.slug === projectId) || D.projects[0];

  return (
    <main className="xs-main">
      <section className="xs-section is-top">
        <button className="xs-back" onClick={() => onNav('projects')}>&lt;- All projects</button>

        <header className="xs-pd-head">
          <MonoLabel color="var(--color-primary-on-dark)">project - {p.category}</MonoLabel>
          <h1 className="xs-pd-title">{p.title}</h1>
          <p className="xs-pd-lead">{p.summary}</p>
          <div className="xs-pd-row">
            <StatusPill>{p.status}</StatusPill>
            <span className="xs-mono" style={{ opacity: 0.6 }}>{p.status_detail.line}</span>
          </div>
        </header>

        <ProjectMediaAlbum project={p} />

        <div className="xs-pd-grid">
          <article>
            <h3 className="xs-pd-h3">Overview</h3>
            <p className="xs-pd-p">{p.overview}</p>

            <h3 className="xs-pd-h3">Key features</h3>
            <ul className="xs-pd-list">
              {p.keyFeatures.map((f, i) => <li key={i}>{f}</li>)}
            </ul>

            <h3 className="xs-pd-h3">Design notes</h3>
            <p className="xs-pd-p">{p.designNotes}</p>

            <h3 className="xs-pd-h3">Technical areas</h3>
            <ul className="xs-pd-list">
              {p.technicalAreas.map((f, i) => <li key={i}>{f}</li>)}
            </ul>
          </article>

          <aside className="xs-pd-side">
            <div className="xs-pd-card">
              <div className="xs-mono" style={{ opacity: 0.6 }}>/ current status</div>
              <div className="xs-pd-card-line">{p.status_detail.line}</div>
              <div className="xs-pd-card-line muted">Next: {p.status_detail.next}</div>
            </div>
            <div className="xs-pd-card">
              <div className="xs-mono" style={{ opacity: 0.6 }}>/ tags</div>
              <div className="xs-tags">{p.tags.map(t => <span key={t} className="xs-tag">{t}</span>)}</div>
            </div>
            <div className="xs-pd-card">
              <div className="xs-mono" style={{ opacity: 0.6 }}>/ links</div>
              <div className="xs-pd-links">
                {(p.links || []).map((l, i) => (
                  <a key={i} href={l.url}>{l.label} &#8599;</a>
                ))}
              </div>
            </div>
          </aside>
        </div>
      </section>
    </main>
  );
}

// ------------------------------------------------------------
// SERVICES
// ------------------------------------------------------------
function ServicesPage() {
  const D = window.XILROS_DATA;
  return (
    <main className="xs-main">
      <section className="xs-section is-top">
        <SectionHead
          eyebrow="services"
          title="Practice areas."
          kicker="These are the things the studio does day to day. Custom briefs welcome - the categories are not a fixed menu."
        />
        <div className="xs-services xs-services-wide">
          {D.services.map((s, i) => (
            <ServiceCard key={s.id} idx={i} title={s.title} desc={s.desc} />
          ))}
        </div>
        <div style={{ marginTop: 48 }}>
          <SupportCard />
        </div>
      </section>
    </main>
  );
}

// ------------------------------------------------------------
// LAB
// ------------------------------------------------------------
function LabPage() {
  const D = window.XILROS_DATA;
  return (
    <main className="xs-main">
      <section className="xs-section is-top">
        <SectionHead
          eyebrow="lab"
          title="XILROS Lab"
          kicker="Build notes, prototype updates, test clips, project visuals, and development logs from ongoing XILROS projects."
        />

        <div className="xs-lab-grid is-2col">
          {D.lab.map(e => <LabCard key={e.id} entry={e} />)}
        </div>

        <div style={{ marginTop: 48 }}>
          <SupportCard />
        </div>
      </section>
    </main>
  );
}

// ------------------------------------------------------------
// CONTACT
// ------------------------------------------------------------
function ContactPage() {
  const D = window.XILROS_DATA;
  return (
    <main className="xs-main">
      <section className="xs-section is-top">
        <SectionHead
          eyebrow="contact"
          title="Contact XILROS"
          kicker="For project inquiries, collaboration ideas, technical questions, or brand-related opportunities."
        />

        {(() => {
          const emailEntry = D.socials.find(s => s.id === 'email') || {};
          const toEmail = emailEntry.handle || 'contact@xilros.com';
          const linkedinPersonal = D.socials.find(s => s.id === 'linkedin-personal') || {};
          return (
            <div className="xs-contact">
              <div className="xs-contact-left">
                <div className="xs-pd-card">
                  <div className="xs-form-head">
                    <MonoLabel color="var(--color-primary-on-dark)">direct</MonoLabel>
                    <p className="xs-pd-p" style={{ marginTop: 4 }}>
                      For project inquiries, collaboration ideas, or technical questions, contact XILROS by email.
                    </p>
                  </div>
                  <Button variant="primary" href={`mailto:${toEmail}`} icon={<SocialIcon name="mail" size={16}/>}>
                    Email {toEmail}
                  </Button>
                </div>
                <div className="xs-pd-card">
                  <div className="xs-mono" style={{ opacity: 0.6 }}>/ channels</div>
                  <div style={{ marginTop: 12 }}>
                    <SocialGrid socials={D.socials} compact />
                  </div>
                </div>
              </div>

              <div className="xs-contact-right">
                <div className="xs-pd-card">
                  <div className="xs-mono" style={{ opacity: 0.6 }}>/ behind XILROS</div>
                  <p className="xs-pd-p" style={{ marginTop: 8 }}>{D.brand.behind}</p>
                  <div style={{ marginTop: 14 }}>
                    <Button
                      variant="secondary"
                      size="sm"
                      href={linkedinPersonal.url || '#'}
                      icon={<SocialIcon name="linkedin" size={16} />}
                    >
                      Connect on LinkedIn
                    </Button>
                  </div>
                </div>

                <SupportCard />
              </div>
            </div>
          );
        })()}
      </section>
    </main>
  );
}

Object.assign(window, {
  HomePage, ProjectsPage, ProjectDetailPage,
  ServicesPage, LabPage, ContactPage,
});
