/* global React, Section, Eyebrow, Button */
// DynamicContent.jsx — CMS-created page sections and blog posts

function CustomSections({
  sections = window.MR_DEFAULT_CONTENT.customSections,
  buttons = window.MR_DEFAULT_CONTENT.buttons,
  onWhatsApp,
}) {
  const published = (sections || []).filter((section) => section.published !== false);
  if (!published.length) return null;

  return (
    <React.Fragment>
      {published.map((section, index) => {
        const reverse = section.layout === 'image-right';
        return (
          <Section key={section.id || index} id={section.id || `seccion-${index + 1}`} bg={index % 2 ? 'cream' : 'white'}>
            <div className={`mr-custom${reverse ? ' mr-custom--reverse' : ''}`}>
              {section.image && (
                <div className="mr-custom__media">
                  <img src={section.image} alt={section.imageAlt || section.title} loading="lazy" />
                </div>
              )}
              <div className="mr-custom__copy">
                {section.eyebrow && <Eyebrow>{section.eyebrow}</Eyebrow>}
                <h2 className="mr-h2">{section.title}</h2>
                <p className="mr-body mr-muted" style={{ marginTop: 18 }}>{section.body}</p>
                {section.ctaLabel && (
                  <div className="mr-custom__actions">
                    <Button
                      variant="secondary"
                      onClick={() => {
                        if (section.ctaHref === 'whatsapp') onWhatsApp();
                        else if (section.ctaHref) window.location.href = section.ctaHref;
                      }}
                    >
                      {section.ctaLabel || buttons.customCta}
                    </Button>
                  </div>
                )}
              </div>
            </div>
          </Section>
        );
      })}
    </React.Fragment>
  );
}

function Blog({ content = window.MR_DEFAULT_CONTENT.blog, buttons = window.MR_DEFAULT_CONTENT.buttons }) {
  const posts = (content.posts || []).filter((post) => post.published !== false);
  const [activePost, setActivePost] = React.useState(null);

  React.useEffect(() => {
    const updateFromHash = () => {
      const match = window.location.hash.match(/^#blog-(.+)$/);
      if (!match) return setActivePost(null);
      setActivePost(posts.find((post) => post.id === match[1]) || null);
    };
    updateFromHash();
    window.addEventListener('hashchange', updateFromHash);
    return () => window.removeEventListener('hashchange', updateFromHash);
  }, [posts]);

  return (
    <Section id="blog" bg="sand">
      <div className="mr-sectionhead">
        <Eyebrow>{content.eyebrow}</Eyebrow>
        <h2 className="mr-h2">{content.title}</h2>
        <p className="mr-lead" style={{ marginTop: 16, maxWidth: '58ch' }}>{content.body}</p>
      </div>

      {posts.length ? (
        <div className="mr-bloggrid">
          {posts.map((post) => (
            <article key={post.id} className="mr-blogcard">
              {post.image && <img src={post.image} alt={post.imageAlt || post.title} loading="lazy" />}
              <div className="mr-blogcard__body">
                <p className="mr-blogcard__meta">{formatDate(post.date)} · {post.author}</p>
                <h3 className="mr-h3">{post.title}</h3>
                <p className="mr-body mr-muted">{post.excerpt}</p>
                <a className="mr-blogcard__link" href={`#blog-${post.id}`}>{buttons.blogRead}</a>
              </div>
            </article>
          ))}
        </div>
      ) : (
        <p className="mr-body mr-muted" style={{ marginTop: 28 }}>{content.emptyText}</p>
      )}

      {activePost && (
        <article className="mr-blogarticle">
          <button className="mr-blogarticle__close" onClick={() => { window.location.hash = '#blog'; }}>
            Cerrar artículo
          </button>
          <p className="mr-blogcard__meta">{formatDate(activePost.date)} · {activePost.author}</p>
          <h3 className="mr-h2">{activePost.title}</h3>
          {activePost.image && <img src={activePost.image} alt={activePost.imageAlt || activePost.title} />}
          <p className="mr-body">{activePost.body}</p>
        </article>
      )}
    </Section>
  );
}

function formatDate(value) {
  if (!value) return '';
  const date = new Date(`${value}T12:00:00`);
  if (Number.isNaN(date.getTime())) return value;
  return date.toLocaleDateString('es-CL', { year: 'numeric', month: 'long', day: 'numeric' });
}

Object.assign(window, { CustomSections, Blog });
