// app/components/Frontend/Container.tsx
'use client';

import { useEffect, useState } from 'react';
import {
  ContainerComponentProps,
  LAYOUT_DEFINITIONS,
  migrateToColumns,
} from '@/lib/page-builder/types';
import { SidebarWidget } from '@/lib/page-builder/container-types';
import { renderSidebarWidget } from '@/lib/page-builder/sidebar-widget-registry';

// ── Padding helper ────────────────────────────────────────────────────────────

function resolvePadding(props: ContainerComponentProps, side: 'top' | 'right' | 'bottom' | 'left'): number {
  if (side === 'top')    return props.paddingTop    ?? props.paddingY ?? 16;
  if (side === 'bottom') return props.paddingBottom ?? props.paddingY ?? 16;
  if (side === 'right')  return props.paddingRight  ?? props.paddingX ?? 16;
  return                        props.paddingLeft   ?? props.paddingX ?? 16;
}

// ── Sidebar hook ──────────────────────────────────────────────────────────────

function useSidebarWidgets(
  savedSidebarId: string | null | undefined,
  inlineWidgets: SidebarWidget[]
): { widgets: SidebarWidget[]; loading: boolean } {
  const [widgets, setWidgets] = useState<SidebarWidget[]>(
    savedSidebarId ? [] : inlineWidgets
  );
  const [loading, setLoading] = useState(!!savedSidebarId);

  useEffect(() => {
    if (!savedSidebarId) {
      setWidgets(inlineWidgets);
      setLoading(false);
      return;
    }
    let active = true;
    setLoading(true);
    fetch(`/api/frontend/sidebars/${savedSidebarId}`)
      .then(r => (r.ok ? r.json() : Promise.reject()))
      .then(data => { if (active) setWidgets(Array.isArray(data.sidebar?.widgets) ? data.sidebar.widgets : []); })
      .catch(() => { if (active) setWidgets(inlineWidgets); })
      .finally(() => { if (active) setLoading(false); });
    return () => { active = false; };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [savedSidebarId]);

  return { widgets, loading };
}

// ── Sidebar component ─────────────────────────────────────────────────────────

function Sidebar({
  savedSidebarId, inlineWidgets, sidebarWidth, sidebarHideOnMobile,
}: {
  savedSidebarId?: string | null;
  inlineWidgets: SidebarWidget[];
  sidebarWidth: number;
  sidebarHideOnMobile: boolean;
}) {
  const { widgets, loading } = useSidebarWidgets(savedSidebarId, inlineWidgets);
  const desktopWidth = sidebarWidth > 0 ? sidebarWidth : 300;

  return (
    <aside
      className={['flex-col gap-6 w-full', sidebarHideOnMobile ? 'hidden lg:flex' : 'flex'].join(' ')}
      style={{ ['--sidebar-w' as string]: `${desktopWidth}px` }}
    >
      <style>{`
        @media (min-width: 1024px) {
          aside[style*="--sidebar-w"] {
            width: var(--sidebar-w) !important;
            min-width: var(--sidebar-w) !important;
            max-width: var(--sidebar-w) !important;
          }
        }
      `}</style>
      {loading ? (
        <div className="space-y-4">
          {[1, 2].map(i => <div key={i} className="h-32 bg-gray-100 rounded-lg animate-pulse" />)}
        </div>
      ) : widgets.length === 0 ? null : (
        <div className="flex flex-col gap-4">
          {widgets.map(widget => <div key={widget.id}>{renderSidebarWidget(widget)}</div>)}
        </div>
      )}
    </aside>
  );
}

// ── Main frontend container ───────────────────────────────────────────────────

interface FrontendContainerProps {
  props: ContainerComponentProps;
  /**
   * For multi-column layouts: one ReactNode per column slot (indexed).
   * Falls back to `children` for full-width / legacy single-column.
   */
  columnChildren?: React.ReactNode[];
  children?: React.ReactNode;
}

export default function FrontendContainer({ props, columnChildren, children }: FrontendContainerProps) {
  const {
    layout = 'full-width',
    savedSidebarId,
    sidebarWidgets = [],
    sidebarHideOnMobile = false,
    sidebarWidth = 300,
    containerPadding = true,
    maxWidth = 1280,
    containerBackground = 'transparent',
    gap = 32,
  } = props;

  const outerStyle = { backgroundColor: containerBackground };

  const innerStyle: React.CSSProperties = {
    maxWidth:      containerPadding ? (maxWidth === 9999 ? 'none' : maxWidth) : 'none',
    paddingTop:    resolvePadding(props, 'top'),
    paddingRight:  containerPadding ? resolvePadding(props, 'right')  : 0,
    paddingBottom: resolvePadding(props, 'bottom'),
    paddingLeft:   containerPadding ? resolvePadding(props, 'left')   : 0,
  };

  const def     = LAYOUT_DEFINITIONS[layout ?? 'full-width'];
  const columns = migrateToColumns(props);

  // ── Sidebar layouts ──────────────────────────────────────────────────────

  if (layout === 'left-sidebar' || layout === 'right-sidebar') {
    const hasSidebar = !!savedSidebarId || sidebarWidgets.length > 0;
    const mainContent = <div className="flex-1 min-w-0">{columnChildren?.[0] ?? children}</div>;
    const sidebarEl = hasSidebar ? (
      <Sidebar
        savedSidebarId={savedSidebarId}
        inlineWidgets={sidebarWidgets}
        sidebarWidth={sidebarWidth}
        sidebarHideOnMobile={sidebarHideOnMobile}
      />
    ) : null;

    return (
      <div className="w-full" style={outerStyle}>
        <div className="mx-auto w-full" style={innerStyle}>
          <div className="flex flex-col lg:flex-row w-full" style={{ gap }}>
            {layout === 'left-sidebar'  ? <>{sidebarEl}{mainContent}</> : <>{mainContent}{sidebarEl}</>}
          </div>
        </div>
      </div>
    );
  }

  // ── Full-width (single column) ───────────────────────────────────────────

  if (layout === 'full-width') {
    return (
      <div className="w-full" style={outerStyle}>
        <div className="mx-auto w-full" style={innerStyle}>
          {columnChildren?.[0] ?? children}
        </div>
      </div>
    );
  }

  // ── Multi-column grid ────────────────────────────────────────────────────
  // Mobile  → flex-col  (each column stacks full-width)
  // Desktop → CSS grid  (fr fractions from the layout definition)
  //
  // gridTemplateColumns is set as an inline style. When the element is
  // display:flex (mobile) it is simply ignored. When Tailwind's lg:grid
  // class switches it to display:grid the property activates automatically —
  // no CSS custom properties or scoped <style> blocks needed.

  return (
    <div className="w-full" style={outerStyle}>
      <div className="mx-auto w-full" style={innerStyle}>
        <div
          className="flex flex-col lg:grid w-full"
          style={{
            gridTemplateColumns: def.fractions.join(' '),
            gap,
          }}
        >
          {columns.map((col, i) => (
            <div key={col.id} className="min-w-0">
              {columnChildren?.[i] ?? null}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}