/*
 * SCR-APPQR 모바일 앱 다운로드 랜딩. 정본: WISE(UIWS) 모바일앱 소개 패턴 이식(#30 보강).
 * 라우트 계약: /app-qr (App.tsx 배선은 통합자 관할 — _workspace/impl_appqr.md 참조).
 *
 * 구성(WISE 모바일앱 소개 컨벤션): ①앱 소개 히어로(제목·설명·QR/설치) ②핵심 기능 카드
 *   ③스크린샷/목업 미리보기 ④설치 안내 스텝 + 요구사항 ⑤스토어 배지(Android APK / iOS 준비중).
 *
 * APK 자체 호스팅: 다운로드 URL = /downloads/kintex.apk (nginx 서빙, 서버 배치는 통합자).
 * 버전 매니페스트 = /downloads/kintex-app.json ({ version, builtAt, size }).
 *   - 200: 히어로에 QR + 버전 + 다운로드/링크복사 노출.
 *   - 404/실패: 히어로 QR 슬롯에 "앱 빌드 준비 중" 빈 상태(EAS 빌드 G3 게이트) — 소개/기능 섹션은 유지.
 * QR은 다운로드 URL을 자체 인코딩(AppQrCode, 외부 API/라이브러리 0).
 */
import { useCallback, useEffect, useState, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import AppQrCode from './AppQrCode';
import { Button } from '../../components/ui/Button';
import { EmptyState, Skeleton } from '../../components/ui/States';
import {
  IconDownload,
  IconCheck,
  IconOperations,
  IconGrid,
  IconWifiOff,
  IconCheckCircle,
  IconShieldCheck,
  IconImage,
  IconDocument,
  IconBell,
} from '../../components/ui/icons';
import './appqr.css';

/** 매니페스트 계약(/downloads/kintex-app.json). 모든 필드 선택 — 부재해도 graceful. */
interface AppManifest {
  version?: string;
  builtAt?: string;
  /** 바이트 수(number) 또는 "24MB" 같은 표기(string) 모두 허용. */
  size?: number | string;
}

const MANIFEST_URL = '/downloads/kintex-app.json';
const APK_URL = '/downloads/kintex.apk';

/** 다운로드 절대 URL — 휴대폰 스캐너가 바로 접근하도록 origin 결합. */
function absoluteApkUrl(): string {
  if (typeof window !== 'undefined' && window.location?.origin) {
    return `${window.location.origin}${APK_URL}`;
  }
  return APK_URL;
}

function formatSize(size?: number | string): string | null {
  if (size == null) return null;
  if (typeof size === 'string') return size;
  if (size <= 0) return null;
  const mb = size / (1024 * 1024);
  return `${mb >= 10 ? Math.round(mb) : mb.toFixed(1)}MB`;
}

type Phase = 'loading' | 'ready' | 'unavailable';

/** 핵심 기능 카드 정의 — 아이콘 + i18n 키(선 SVG, 이모지 0). */
interface Feature {
  key: string;
  icon: ReactNode;
}
const FEATURES: Feature[] = [
  { key: 'checkin', icon: <IconCheckCircle size={22} /> },
  { key: 'inspection', icon: <IconShieldCheck size={22} /> },
  { key: 'gallery', icon: <IconImage size={22} /> },
  { key: 'approval', icon: <IconDocument size={22} /> },
  { key: 'notify', icon: <IconBell size={22} /> },
  { key: 'offline', icon: <IconWifiOff size={22} /> },
];

/** 미리보기 목업 프레임 — 실제 스크린샷 부재 시 아이콘 플레이스홀더(있으면 이미지로 교체). */
const PREVIEWS: Feature[] = [
  { key: 's1', icon: <IconCheckCircle size={30} /> },
  { key: 's2', icon: <IconImage size={30} /> },
  { key: 's3', icon: <IconDocument size={30} /> },
];

export function AppQrCodePage() {
  const { t } = useTranslation();
  const [phase, setPhase] = useState<Phase>('loading');
  const [manifest, setManifest] = useState<AppManifest | null>(null);
  const [copied, setCopied] = useState(false);

  const load = useCallback(async () => {
    setPhase('loading');
    try {
      const res = await fetch(MANIFEST_URL, { cache: 'no-store' });
      if (!res.ok) {
        // 404 = APK 미빌드(G3 게이트). "빌드 준비 중" 상태로 정직 표기.
        setManifest(null);
        setPhase('unavailable');
        return;
      }
      const data = (await res.json()) as AppManifest;
      setManifest(data);
      setPhase('ready');
    } catch {
      // 네트워크/파싱 실패도 동일하게 미가용 처리(외부 QR 서비스 호출 없음).
      setManifest(null);
      setPhase('unavailable');
    }
  }, []);

  useEffect(() => {
    void load();
  }, [load]);

  const copyLink = async () => {
    try {
      await navigator.clipboard.writeText(absoluteApkUrl());
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch {
      /* clipboard 권한 없을 때 무시 */
    }
  };

  const version = manifest?.version ?? null;
  const builtAt = manifest?.builtAt ?? null;
  const sizeLabel = formatSize(manifest?.size);

  const steps = [
    t('appqr.steps.s1'),
    t('appqr.steps.s2'),
    t('appqr.steps.s3'),
    t('appqr.steps.s4'),
  ];

  const requirements = [
    t('appqr.requirements.os'),
    t('appqr.requirements.space'),
    t('appqr.requirements.network'),
  ];

  return (
    <main className="kx-page kx-appqr">
      {/* ── ① 앱 소개 히어로 ── */}
      <section className="kx-appqr__hero">
        <div className="kx-appqr__hero-text">
          <span className="kx-appqr__eyebrow">{t('appqr.eyebrow')}</span>
          <h1 className="kx-appqr__title">{t('appqr.title')}</h1>
          <p className="kx-appqr__subtitle">{t('appqr.subtitle')}</p>
          <p className="kx-appqr__intro">{t('appqr.intro')}</p>

          <div className="kx-appqr__chips">
            <span className="kx-appqr__chip">{t('appqr.platformChip')}</span>
            {version ? <span className="kx-appqr__chip">v{version}</span> : null}
            {sizeLabel ? (
              <span className="kx-appqr__chip">{t('appqr.about', { size: sizeLabel })}</span>
            ) : null}
          </div>

          {phase === 'ready' ? (
            <>
              <div className="kx-appqr__actions">
                <a className="kx-btn kx-btn--primary" href={APK_URL} download="kintex.apk">
                  <span className="kx-btn__icon" aria-hidden="true">
                    <IconDownload size={15} />
                  </span>
                  {t('appqr.download')}
                </a>
                <Button
                  variant="secondary"
                  onClick={copyLink}
                  leadingIcon={copied ? <IconCheck size={15} /> : undefined}
                >
                  {copied ? t('appqr.copied') : t('appqr.copyLink')}
                </Button>
                <Button
                  variant="ghost"
                  onClick={() => void load()}
                  leadingIcon={<IconOperations size={15} />}
                >
                  {t('appqr.refresh')}
                </Button>
              </div>
              {builtAt ? (
                <p className="kx-appqr__meta">{t('appqr.builtAt', { date: builtAt })}</p>
              ) : null}
            </>
          ) : null}
        </div>

        {/* 히어로 QR 슬롯 — phase별 로딩/미가용/QR */}
        <div className="kx-appqr__hero-qr">
          {phase === 'loading' ? (
            <div className="kx-card kx-appqr__qr-card">
              <Skeleton height={200} width={200} radius={8} />
              <Skeleton height={16} width={160} />
            </div>
          ) : phase === 'unavailable' ? (
            <div className="kx-card kx-appqr__qr-card">
              <EmptyState
                icon={<IconWifiOff size={40} />}
                title={t('appqr.notReady.title')}
                description={t('appqr.notReady.desc')}
                action={
                  <Button variant="secondary" onClick={() => void load()}>
                    {t('appqr.retry')}
                  </Button>
                }
              />
            </div>
          ) : (
            <div className="kx-card kx-appqr__qr-card">
              <div className="kx-appqr__qr">
                {/* 다운로드 URL을 자체 인코딩한 QR(외부 API 0). */}
                <AppQrCode value={absoluteApkUrl()} size={200} title={t('appqr.qrAlt')} />
              </div>
              <div className="kx-appqr__name-row">
                <IconGrid size={18} />
                <span className="kx-appqr__name">{t('appqr.appName')}</span>
              </div>
              <p className="kx-appqr__qr-hint">{t('appqr.qrHint')}</p>
            </div>
          )}
        </div>
      </section>

      {/* ── ② 핵심 기능 카드 ── */}
      <section className="kx-appqr__section" aria-label={t('appqr.features.heading')}>
        <h2 className="kx-appqr__section-title">{t('appqr.features.heading')}</h2>
        <p className="kx-appqr__section-sub">{t('appqr.features.sub')}</p>
        <div className="kx-appqr__features">
          {FEATURES.map((f) => (
            <div key={f.key} className="kx-card kx-appqr__feature">
              <span className="kx-appqr__feature-icon" aria-hidden="true">
                {f.icon}
              </span>
              <div className="kx-appqr__feature-body">
                <h3 className="kx-appqr__feature-title">
                  {t(`appqr.features.${f.key}.title`)}
                </h3>
                <p className="kx-appqr__feature-desc">
                  {t(`appqr.features.${f.key}.desc`)}
                </p>
              </div>
            </div>
          ))}
        </div>
      </section>

      {/* ── ③ 스크린샷/목업 미리보기 ── */}
      <section className="kx-appqr__section" aria-label={t('appqr.preview.heading')}>
        <h2 className="kx-appqr__section-title">{t('appqr.preview.heading')}</h2>
        <p className="kx-appqr__section-sub">{t('appqr.preview.sub')}</p>
        <div className="kx-appqr__previews">
          {PREVIEWS.map((p) => (
            <figure key={p.key} className="kx-appqr__preview">
              <div className="kx-appqr__preview-frame" aria-hidden="true">
                <span className="kx-appqr__preview-icon">{p.icon}</span>
              </div>
              <figcaption className="kx-appqr__preview-cap">
                {t(`appqr.preview.${p.key}`)}
              </figcaption>
            </figure>
          ))}
        </div>
      </section>

      {/* ── ④ 설치 안내 + ⑤ 요구사항/스토어 배지 ── */}
      <section className="kx-appqr__section kx-appqr__install">
        <div className="kx-appqr__install-col">
          <h2 className="kx-appqr__section-title">{t('appqr.steps.heading')}</h2>
          <ol className="kx-appqr__steps">
            {steps.map((s, i) => (
              <li key={i} className="kx-appqr__step">
                <span className="kx-appqr__step-num" aria-hidden="true">
                  {i + 1}
                </span>
                <span className="kx-appqr__step-text">{s}</span>
              </li>
            ))}
          </ol>
        </div>

        <div className="kx-appqr__install-col">
          <h2 className="kx-appqr__section-title">{t('appqr.requirements.heading')}</h2>
          <ul className="kx-appqr__reqs">
            {requirements.map((r, i) => (
              <li key={i} className="kx-appqr__req">
                <span className="kx-appqr__req-icon" aria-hidden="true">
                  <IconCheck size={15} />
                </span>
                <span>{r}</span>
              </li>
            ))}
          </ul>

          <div className="kx-appqr__badges">
            <div className="kx-appqr__badge kx-appqr__badge--android">
              <span className="kx-appqr__badge-icon" aria-hidden="true">
                <IconDownload size={20} />
              </span>
              <div className="kx-appqr__badge-text">
                <span className="kx-appqr__badge-sub">{t('appqr.store.getOn')}</span>
                <span className="kx-appqr__badge-main">{t('appqr.store.android')}</span>
              </div>
            </div>
            <div className="kx-appqr__badge kx-appqr__badge--ios">
              <span className="kx-appqr__badge-icon" aria-hidden="true">
                <IconShieldCheck size={20} />
              </span>
              <div className="kx-appqr__badge-text">
                <span className="kx-appqr__badge-sub">{t('appqr.store.comingSoon')}</span>
                <span className="kx-appqr__badge-main">{t('appqr.store.ios')}</span>
              </div>
            </div>
          </div>
          <p className="kx-appqr__ios">{t('appqr.iosNote')}</p>
        </div>
      </section>
    </main>
  );
}

export default AppQrCodePage;
