/*
 * SCR-36 참가업체 마이크로사이트 편집기 [M17]. 참조: design.md §3 SCR-36.
 * 좌: 섹션 편집(표시/숨김)·테마 · 중: 라이브 프리뷰(데스크톱/모바일) · 우: 게시 상태·URL·SEO·언어·저장/배포.
 * ★실 API 전환: GET/PUT /api/exhibitors/{exhibitorId}/microsite. 섹션·테마·SEO·상태 저장 실동작(공개 뷰 = /api/public/microsites/{id}).
 * 나노바나나 예상샷 갤러리는 AiLabel 워터마크(미배선 렌더). 데모 참가업체 = 'hanbit'(V19 시드).
 */
import { useEffect, useState } from 'react';
import { Button } from '../../components/ui/Button';
import { AiLabel } from '../../components/ui/Badge';
import { ApiRequestError } from '../../api/client';
import { cmsApi, type Microsite, type MicrositeSection } from './cmsApi';
import {
  IconImage,
  IconPlus,
  IconWarning,
  IconGrid,
  IconExpand,
  IconDownload,
} from '../../components/ui/icons';
import './cms.css';

type Lang = 'ko' | 'en' | 'zh' | 'ja';
const LANGS: { key: Lang; label: string }[] = [
  { key: 'ko', label: '한' },
  { key: 'en', label: '영' },
  { key: 'zh', label: '중' },
  { key: 'ja', label: '일' },
];

const THEMES = [
  { key: 'blue', color: 'var(--color-primary-600)' },
  { key: 'violet', color: 'var(--color-ai-accent)' },
  { key: 'green', color: 'var(--color-success)' },
  { key: 'red', color: 'var(--color-error)' },
];

// 데모 참가업체(라우트 param 미배선 트랙 — V19 시드 'hanbit').
const DEMO_EXHIBITOR_ID = 'hanbit';

function MiniIcon({ d, size = 16 }: { d: string; size?: number }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <path d={d} />
    </svg>
  );
}
const D_DRAG = 'M9 5h.01M9 12h.01M9 19h.01M15 5h.01M15 12h.01M15 19h.01';
const D_EYE = 'M2 12s4-7 10-7 10 7 10 7-4 7-10 7-10-7-10-7z M12 12h.01';
const D_COPY = 'M9 9h10v10H9z M5 15H4V4h11v1';

const SECTION_NAMES: Record<string, string> = {
  intro: '부스 소개',
  products: '제품',
  gallery: '예상샷 갤러리',
  contact: '연락처',
  meeting: '미팅 예약',
};

export function MicrositeBuilderPage() {
  const [site, setSite] = useState<Microsite | null>(null);
  const [sections, setSections] = useState<MicrositeSection[]>([]);
  const [activeSection, setActiveSection] = useState<string | null>(null);
  const [device, setDevice] = useState<'desktop' | 'mobile'>('desktop');
  const [theme, setTheme] = useState('blue');
  const [lang, setLang] = useState<Lang>('ko');
  const [title, setTitle] = useState('');
  const [meta, setMeta] = useState('');
  const [loading, setLoading] = useState(true);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [notice, setNotice] = useState<string | null>(null);

  useEffect(() => {
    (async () => {
      setLoading(true);
      setError(null);
      try {
        const m = await cmsApi.getMicrosite(DEMO_EXHIBITOR_ID);
        applySite(m);
      } catch (e) {
        setError(e instanceof ApiRequestError ? e.message : '마이크로사이트를 불러오지 못했습니다.');
      } finally {
        setLoading(false);
      }
    })();
  }, []);

  function applySite(m: Microsite) {
    setSite(m);
    const secs = Array.isArray(m.sections) ? m.sections : [];
    setSections(secs);
    setActiveSection(secs[0]?.id ?? null);
    setTheme(m.theme || 'blue');
    setTitle(m.seoTitle ?? '');
    setMeta(m.seoMeta ?? '');
  }

  async function persist(status: 'draft' | 'published') {
    if (!site) return;
    setBusy(true);
    setError(null);
    setNotice(null);
    try {
      const saved = await cmsApi.saveMicrosite(DEMO_EXHIBITOR_ID, {
        eventId: site.eventId,
        slug: site.slug,
        exhibitorName: site.exhibitorName,
        theme,
        sections,
        seoTitle: title,
        seoMeta: meta,
        langs: site.langs,
        status,
      });
      applySite(saved);
      setNotice(status === 'published' ? '마이크로사이트를 배포했습니다.' : '변경 사항을 저장했습니다.');
    } catch (e) {
      setError(e instanceof ApiRequestError ? e.message : '저장에 실패했습니다.');
    } finally {
      setBusy(false);
    }
  }

  const brand = site?.exhibitorName ?? '(주)한빛로보틱스';

  return (
    <div className="kx-page">
      <header className="kx-cms__head">
        <div>
          <h1 className="kx-cms__title">마이크로사이트 빌더</h1>
          <p className="kx-cms__subtitle">{brand} · 참가업체 공개 소개 페이지(부스·제품·연락) 편집</p>
        </div>
        <div className="kx-cms__head-actions">
          <Button variant="secondary" leadingIcon={<IconExpand size={16} />} onClick={() => persist('draft')} disabled={busy || loading}>
            저장
          </Button>
          <Button onClick={() => persist('published')} disabled={busy || loading}>
            배포하기
          </Button>
        </div>
      </header>

      {error && (
        <div className="kx-cms-alert" role="alert">
          <IconWarning size={14} /> {error}
        </div>
      )}
      {notice && (
        <div className="kx-cms-alert kx-cms-alert--ok" role="status">
          {notice}
        </div>
      )}

      <div className="kx-mb-grid">
        {/* 좌: 섹션 편집 + 테마 */}
        <section className="kx-card kx-cms-col kx-mb-sections" aria-label="섹션 편집">
          <div className="kx-cms-sublabel">섹션 편집</div>
          {loading ? (
            <div className="kx-cms-empty">불러오는 중…</div>
          ) : (
            <ul className="kx-mb-sec">
              {sections.map((s) => (
                <li key={s.id}>
                  <button
                    className={`kx-mb-sec__item ${s.id === activeSection ? 'is-active' : ''}`}
                    onClick={() => setActiveSection(s.id)}
                    aria-current={s.id === activeSection}
                  >
                    <span className="kx-mb-sec__label">
                      <MiniIcon d={D_DRAG} />
                      {SECTION_NAMES[s.type] ?? s.type}
                    </span>
                    <span className="kx-mb-sec__ctrls">
                      <span
                        className={`kx-icon-btn ${s.visible ? '' : 'is-off'}`}
                        title={s.visible ? '표시 중 (클릭하여 숨김)' : '숨김 (클릭하여 표시)'}
                        role="button"
                        tabIndex={0}
                        aria-pressed={s.visible}
                        onClick={(e) => {
                          e.stopPropagation();
                          setSections((prev) =>
                            prev.map((x) => (x.id === s.id ? { ...x, visible: !x.visible } : x)),
                          );
                        }}
                        onKeyDown={(e) => {
                          if (e.key === 'Enter' || e.key === ' ') {
                            e.preventDefault();
                            setSections((prev) =>
                              prev.map((x) => (x.id === s.id ? { ...x, visible: !x.visible } : x)),
                            );
                          }
                        }}
                      >
                        <MiniIcon d={D_EYE} />
                      </span>
                    </span>
                  </button>
                </li>
              ))}
            </ul>
          )}
          <button
            className="kx-mb-addbtn"
            onClick={() =>
              setSections((prev) => [
                ...prev,
                { id: `sec-${Date.now()}`, type: 'intro', visible: true, order: prev.length, payload: {} },
              ])
            }
          >
            <IconPlus size={16} /> 섹션 추가
          </button>

          <div className="kx-cms-sublabel" style={{ marginTop: 8 }}>
            테마 설정
          </div>
          <div className="kx-cms-field">
            <span className="kx-cms-label">기본 색상</span>
            <div className="kx-mb-swatches">
              {THEMES.map((t) => (
                <button
                  key={t.key}
                  className={`kx-mb-swatch ${theme === t.key ? 'is-active' : ''}`}
                  style={{ background: t.color }}
                  onClick={() => setTheme(t.key)}
                  title={`테마 ${t.key}`}
                  aria-label={`테마 ${t.key}`}
                  aria-pressed={theme === t.key}
                />
              ))}
            </div>
          </div>
        </section>

        {/* 중: 캔버스 프리뷰 */}
        <section aria-label="라이브 미리보기">
          <div className="kx-mb-canvas">
            <div className="kx-mb-devicebar kx-seg" role="tablist" aria-label="디바이스">
              <button
                role="tab"
                aria-selected={device === 'desktop'}
                className={`kx-seg__btn ${device === 'desktop' ? 'is-active' : ''}`}
                onClick={() => setDevice('desktop')}
              >
                데스크톱
              </button>
              <button
                role="tab"
                aria-selected={device === 'mobile'}
                className={`kx-seg__btn ${device === 'mobile' ? 'is-active' : ''}`}
                onClick={() => setDevice('mobile')}
              >
                모바일
              </button>
            </div>

            <div className={`kx-mb-frame ${device === 'mobile' ? 'kx-mb-frame--mobile' : ''}`}>
              <div className="kx-mb-site__nav">
                <div className="kx-mb-site__brand">
                  <span className="kx-mb-site__logo">{brand.replace(/[^가-힣A-Za-z]/g, '').charAt(0) || 'H'}</span>
                  {brand}
                </div>
                <nav className="kx-mb-site__menu">
                  {sections.filter((s) => s.visible).map((s) => (
                    <span key={s.id}>{SECTION_NAMES[s.type] ?? s.type}</span>
                  ))}
                </nav>
              </div>

              <section className="kx-mb-hero">
                <div>
                  <span className="kx-mb-hero__eyebrow">KINTEX AI EXPO</span>
                  <h2 className="kx-mb-hero__title">
                    {(sections.find((s) => s.type === 'intro')?.payload?.headline as string) ??
                      '지능형 로보틱스의 새로운 지평을 열다'}
                  </h2>
                  <p className="kx-mb-hero__desc">
                    {(sections.find((s) => s.type === 'intro')?.payload?.desc as string) ??
                      '산업용 로봇부터 서비스 자동화 솔루션까지, 미래 모빌리티 생태계를 경험하세요.'}
                  </p>
                  <div className="kx-mb-hero__cta">
                    <span className="kx-mb-btn kx-mb-btn--solid">미팅 예약하기</span>
                    <span className="kx-mb-btn kx-mb-btn--ghost">브로슈어 다운로드</span>
                  </div>
                </div>
              </section>

              {sections.some((s) => s.visible && s.type === 'products') && (
                <section className="kx-mb-section kx-mb-section--alt">
                  <div className="kx-mb-section__head">
                    <span className="kx-mb-section__bar" />
                    <h3 className="kx-mb-section__title">주요 혁신 제품</h3>
                  </div>
                  <div className="kx-mb-cards">
                    <article className="kx-mb-card">
                      <div className="kx-mb-card__img">
                        <IconImage size={24} />
                        <span className="kx-mb-card__tag">NEW</span>
                      </div>
                      <div className="kx-mb-card__body">
                        <div className="kx-mb-card__title">HR-A1 협동로봇</div>
                        <p className="kx-mb-card__desc">고정밀 센서·AI 비전 시스템 탑재 다목적 협동로봇.</p>
                      </div>
                    </article>
                    <article className="kx-mb-card">
                      <div className="kx-mb-card__img">
                        <IconImage size={24} />
                        <span className="kx-mb-card__tag">POPULAR</span>
                      </div>
                      <div className="kx-mb-card__body">
                        <div className="kx-mb-card__title">ServiBot Elite</div>
                        <p className="kx-mb-card__desc">전시장·호텔용 지능형 서비스 로봇.</p>
                      </div>
                    </article>
                  </div>
                </section>
              )}

              {sections.some((s) => s.visible && s.type === 'gallery') && (
                <section className="kx-mb-section">
                  <div className="kx-mb-section__head">
                    <span className="kx-mb-section__bar" style={{ background: 'var(--color-ai-accent)' }} />
                    <h3 className="kx-mb-section__title">AI 부스 예상 시뮬레이션</h3>
                  </div>
                  <div className="kx-mb-gallery">
                    <div className="kx-mb-gallery__cell">
                      <IconGrid size={28} />
                      <span className="kx-mb-gallery__wm">
                        <AiLabel>AI 생성 예상</AiLabel>
                      </span>
                    </div>
                    <div className="kx-mb-gallery__cell">
                      <IconGrid size={28} />
                      <span className="kx-mb-gallery__wm">
                        <AiLabel>AI 생성 예상</AiLabel>
                      </span>
                    </div>
                  </div>
                </section>
              )}
            </div>
          </div>
        </section>

        {/* 우: 게시·SEO */}
        <aside className="kx-card kx-mb-side" aria-label="게시 및 SEO">
          <div className="kx-mb-side__section">
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <span className="kx-cms-sublabel">사이트 상태</span>
              <span className={`kx-mb-status ${site?.status === 'published' ? '' : 'kx-mb-status--draft'}`}>
                <span className="kx-mb-status__dot" /> {site?.status === 'published' ? '게시됨' : '초안'}
              </span>
            </div>
            <span className="kx-cms-label">공개 URL</span>
            <div className="kx-mb-url">
              <span>{site?.slug ? `${site.slug}.expo.kintex.kr` : '슬러그 미설정'}</span>
              <button className="kx-icon-btn" title="URL 복사" aria-label="URL 복사"
                onClick={() => site?.slug && void navigator.clipboard?.writeText(`${site.slug}.expo.kintex.kr`)}>
                <MiniIcon d={D_COPY} />
              </button>
            </div>
          </div>

          <div className="kx-mb-side__section">
            <span className="kx-cms-sublabel">SEO · 검색 엔진</span>
            <label className="kx-cms-field">
              <span className="kx-cms-label">페이지 타이틀</span>
              <input className="kx-cms-input" value={title} onChange={(e) => setTitle(e.target.value)} />
            </label>
            <label className="kx-cms-field">
              <span className="kx-cms-label">메타 설명</span>
              <textarea className="kx-cms-textarea" value={meta} onChange={(e) => setMeta(e.target.value)} />
            </label>
          </div>

          <div className="kx-mb-side__section">
            <span className="kx-cms-sublabel">언어 설정</span>
            <div className="kx-seg" role="tablist" aria-label="언어">
              {LANGS.map((l) => (
                <button
                  key={l.key}
                  role="tab"
                  aria-selected={lang === l.key}
                  className={`kx-seg__btn ${lang === l.key ? 'is-active' : ''}`}
                  onClick={() => setLang(l.key)}
                >
                  {l.label}
                </button>
              ))}
            </div>
          </div>

          <Button block leadingIcon={<IconDownload size={16} />} style={{ marginTop: 'auto' }}
            onClick={() => persist('published')} disabled={busy || loading}>
            전시 라이브 적용
          </Button>
        </aside>
      </div>
    </div>
  );
}
