import { mediaUrl, mediaAlt } from '@/lib/payload'
import type { Product, HomePage } from '@/payload-types'

type Props = {
  products: Product[]
  home: HomePage | null
  openPanelSlug?: string
}

function splitOn(str: string | undefined | null, fallback: string): string[] {
  return (str || fallback).split('|')
}

function multiLine(str: string | undefined | null, fallback: string): string {
  return (str || fallback).replace(/\n/g, '<br>')
}

export default function ReboursPage({ products, home, openPanelSlug }: Props) {
  const heroImg =
    mediaUrl(home?.heroImage as never, 'feature') ||
    (products[0]?.images?.[0] ? mediaUrl((products[0].images[0] as { image: unknown }).image as never, 'feature') : null) ||
    '/assets/table-terrazzo.jpg'
  const heroImgAlt = mediaAlt(home?.heroImage as never, 'REBOURS — Mobilier d\u2019art contemporain, Paris 2026')

  const heroLabel = home?.heroLabel || '// ARCHIVE_001 — 2026'
  const heroTitleParts = splitOn(home?.heroTitle, 'REBOURS|STUDIO')
  const heroSubtitle = multiLine(home?.heroSubtitle, 'Mobilier d\u2019art contemporain.\nSpace Age × Memphis.')
  const heroStatus = multiLine(home?.heroStatus, 'STATUS: [PROTOTYPE EN COURS]\nCOLLECTION_001 — BIENTÔT DISPONIBLE')

  const collectionLabel = home?.collectionLabel || '// COLLECTION_001'
  const collectionCta = home?.collectionCta || 'CLIQUER POUR OUVRIR'

  const contactLabel = home?.contactLabel || '// CONTACT'
  const contactTitleParts = splitOn(home?.contactTitle, 'UNE QUESTION ?|PARLONS-EN')
  const contactDesc = multiLine(home?.contactDescription, 'Commandes sur mesure, questions techniques,\nou simplement dire bonjour.')
  const whatsappNumber = home?.whatsappNumber || '33651755191'
  const whatsappBtnText = home?.whatsappButtonText || 'CONTACTEZ-NOUS SUR WHATSAPP'
  const contactResponseTime = home?.contactResponseTime || 'RÉPONSE SOUS 24H'

  const footerText = home?.footerText || '© 2026 REBOURS STUDIO — PARIS'
  const instagramUrl = home?.instagramUrl || 'https://instagram.com/rebour.studio'

  return (
    <>
      {openPanelSlug && (
        <script
          dangerouslySetInnerHTML={{
            __html: `window.__OPEN_PANEL__ = ${JSON.stringify(openPanelSlug)};`,
          }}
        />
      )}

      <div id="interactive-grid" className="interactive-grid"></div>

      <div id="product-panel" className="product-panel" aria-hidden="true">
        <div className="panel-close" id="panel-close">
          <span>← RETOUR</span>
        </div>
        <div className="panel-inner">
          <div className="panel-img-col">
            <div className="panel-gallery" id="panel-gallery">
              <img id="panel-img" src="" alt="Image produit REBOURS Studio" />
            </div>
            <div className="panel-gallery-nav" id="panel-gallery-nav"></div>
          </div>
          <div className="panel-info-col">
            <p className="panel-index" id="panel-index"></p>
            <h2 id="panel-name"></h2>
            <hr />
            <div className="panel-meta">
              <div className="panel-meta-row">
                <span className="meta-key">TYPE</span>
                <span id="panel-type"></span>
              </div>
              <div className="panel-meta-row">
                <span className="meta-key">MATÉRIAUX</span>
                <span id="panel-mat"></span>
              </div>
              <div className="panel-meta-row">
                <span className="meta-key">ANNÉE</span>
                <span id="panel-year"></span>
              </div>
              <div className="panel-meta-row">
                <span className="meta-key">STATUS</span>
                <span id="panel-status" className="red"></span>
              </div>
            </div>
            <hr />
            <p id="panel-desc" className="panel-desc"></p>
            <hr />

            <details className="accordion" open>
              <summary>
                SPÉCIFICATIONS TECHNIQUES <span>↓</span>
              </summary>
              <div className="accordion-body" id="panel-specs"></div>
            </details>
            <details className="accordion" open>
              <summary>
                NOTES DE CONCEPTION <span>↓</span>
              </summary>
              <div className="accordion-body" id="panel-notes"></div>
            </details>

            <hr />

            <div id="checkout-section" style={{ display: 'none' }}>
              <div className="checkout-price-line">
                <span className="checkout-price"></span>
                <span className="checkout-edition">ÉDITION UNIQUE — 1/1</span>
              </div>
              <button id="checkout-toggle-btn" className="checkout-btn">
                [ COMMANDER CETTE PIÈCE ]
              </button>
              <div id="checkout-form-wrap" className="checkout-form-wrap" style={{ display: 'none' }}>
                <form id="checkout-form" className="checkout-form">
                  <div className="checkout-form-field">
                    <label htmlFor="checkout-email">EMAIL *</label>
                    <input type="email" id="checkout-email" name="email" placeholder="votre@email.com" required autoComplete="off" />
                  </div>
                  <div className="checkout-form-note">
                    Pièce fabriquée à Paris. Délai : 6 à 8 semaines.<br />
                    Paiement sécurisé via Stripe.
                  </div>
                  <button type="submit" className="checkout-submit" id="checkout-submit-btn">
                    PROCÉDER AU PAIEMENT →
                  </button>
                </form>
              </div>
            </div>

            <div className="panel-footer">
              <span className="blink">■</span> COLLECTION_001 — W.I.P
            </div>
          </div>
        </div>
      </div>

      <div className="page-wrapper">
        <header className="header">
          <a href="/" className="logo-text" aria-label="REBOURS — Accueil">
            REBOURS
          </a>
          <nav className="header-nav" aria-label="Navigation principale">
            <a href="#collection">COLLECTION_001</a>
            <a href="#" className="contact-trigger">
              CONTACT
            </a>
            <span className="wip-tag">
              <span className="blink">■</span> W.I.P
            </span>
          </nav>
        </header>

        <main>
          <section className="hero" aria-label="Introduction">
            <div className="hero-left">
              <p className="label">{heroLabel}</p>
              <h1>
                {heroTitleParts.map((part, i) => (
                  <span key={i}>
                    {i > 0 && <br />}
                    {part}
                  </span>
                ))}
              </h1>
              <p className="hero-sub" dangerouslySetInnerHTML={{ __html: heroSubtitle }} />
              <p className="hero-sub mono-sm" dangerouslySetInnerHTML={{ __html: heroStatus }} />
            </div>
            <div className="hero-right">
              <img src={heroImg} alt={heroImgAlt} className="hero-img" width="1024" height="1024" fetchPriority="high" />
            </div>
          </section>

          <hr />

          <section className="collection" id="collection" aria-label="Collection 001">
            <div className="collection-header">
              <p className="label">{collectionLabel}</p>
              <span className="label">
                {products.length} OBJETS — {collectionCta}
              </span>
            </div>

            <div className="product-grid">
              {products.map((p, i) => {
                const imageEntries = (p.images || []) as Array<{ image: unknown }>
                const mainImage = imageEntries[0]?.image
                const imgUrl = mediaUrl(mainImage as never, 'card') || ''
                const fullImgUrl = mediaUrl(mainImage as never, 'feature') || ''
                const alt = mediaAlt(mainImage as never, `${p.productDisplayName} — mobilier d\u2019art contemporain, REBOURS Studio Paris`)
                const allImgs = imageEntries
                  .map((entry) => {
                    const url = mediaUrl(entry.image as never, 'feature')
                    if (!url) return null
                    return { url, alt: mediaAlt(entry.image as never, alt) }
                  })
                  .filter((x): x is { url: string; alt: string } => !!x)

                return (
                  <article
                    key={p.id}
                    className="product-card"
                    data-index={p.index}
                    data-name={p.name}
                    data-type={p.type}
                    data-mat={p.materials}
                    data-year={p.year}
                    data-status={p.status}
                    data-desc={p.description}
                    data-specs={p.specs || ''}
                    data-notes={p.notes || ''}
                    data-img={fullImgUrl}
                    data-images={JSON.stringify(allImgs)}
                    data-price={p.price ? String(p.price) : ''}
                    data-slug={p.slug}
                    data-img-alt={alt}
                    aria-label={`Ouvrir le détail de ${p.productDisplayName}`}
                  >
                    <div className="card-img-wrap">
                      <img src={imgUrl} alt={alt} width="600" height="600" loading={i === 0 ? 'eager' : 'lazy'} />
                    </div>
                    <div className="card-meta">
                      <span className="card-index">{String(i + 1).padStart(3, '0')}</span>
                      <span className="card-name">{p.name}</span>
                      <span className="card-arrow">↗</span>
                    </div>
                  </article>
                )
              })}
            </div>
          </section>

          <section className="newsletter" id="contact" aria-label="Contact WhatsApp">
            <div className="nl-left">
              <p className="label">{contactLabel}</p>
              <h2>
                {contactTitleParts.map((part, i) => (
                  <span key={i}>
                    {i > 0 && <br />}
                    {part}
                  </span>
                ))}
              </h2>
            </div>
            <div className="nl-right">
              <div className="nl-form" style={{ pointerEvents: 'auto' }}>
                <p className="mono-sm" style={{ lineHeight: 1.9, marginBottom: '0.5rem' }} dangerouslySetInnerHTML={{ __html: contactDesc }} />
                <a href={`https://wa.me/${whatsappNumber}`} target="_blank" rel="noopener" className="whatsapp-btn" aria-label="Nous contacter sur WhatsApp">
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor" style={{ flexShrink: 0 }}>
                    <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z" />
                  </svg>
                  {whatsappBtnText}
                </a>
                <p className="mono-sm">
                  <span className="blink">■</span> {contactResponseTime}
                </p>
              </div>
            </div>
          </section>
        </main>

        <footer className="footer">
          <span>{footerText}</span>
          <nav aria-label="Liens secondaires">
            <a href={instagramUrl} rel="noopener" target="_blank">
              INSTAGRAM
            </a>
            &nbsp;/&nbsp;
            <a href="#" className="contact-trigger">
              CONTACT
            </a>
          </nav>
        </footer>
      </div>

      <div id="contact-modal" className="contact-modal" aria-hidden="true" data-whatsapp={whatsappNumber}>
        <div className="contact-modal-backdrop"></div>
        <div className="contact-modal-content">
          <div className="contact-modal-header">
            <p className="label">// CONTACT</p>
            <button className="contact-modal-close" aria-label="Fermer">
              ✕
            </button>
          </div>
          <hr />
          <h2 className="contact-modal-title">
            ENVOYER
            <br />
            UN MESSAGE
          </h2>
          <form id="contact-form" className="contact-form">
            <div className="contact-field">
              <label htmlFor="contact-name">NOM *</label>
              <input type="text" id="contact-name" name="name" placeholder="Votre nom" required autoComplete="name" />
            </div>
            <div className="contact-field">
              <label htmlFor="contact-email">EMAIL *</label>
              <input type="email" id="contact-email" name="email" placeholder="votre@email.com" required autoComplete="email" />
            </div>
            <div className="contact-field">
              <label htmlFor="contact-subject">OBJET</label>
              <input type="text" id="contact-subject" name="subject" placeholder="Objet du message" autoComplete="off" />
            </div>
            <div className="contact-field">
              <label htmlFor="contact-message">MESSAGE *</label>
              <textarea id="contact-message" name="message" rows={5} placeholder="Votre message..." required />
            </div>
            <button type="submit" className="contact-submit">
              ENVOYER LE MESSAGE →
            </button>
            <p className="mono-sm contact-note">
              <span className="blink">■</span> REDIRECTION VERS WHATSAPP
            </p>
          </form>
        </div>
      </div>

      <div className="cursor-dot"></div>
      <div className="cursor-outline"></div>
    </>
  )
}
