import React from 'react';

interface Screen {
  name: string;
  type: string;
}

interface MobileScreenListProps {
  screens: Screen[];
  color: string;
  slug: string;
}

const TYPE_LABEL: Record<string, string> = {
  customer: '사용자',
  admin: '관리자',
  field: '현장',
};

/* --- 화면 이름 키워드로 UI 레이아웃 결정 --- */
type Layout = 'dashboard' | 'list' | 'chart' | 'form' | 'kanban';

function guessLayout(name: string): Layout {
  const n = name;
  if (/대시보드|현황|KPI|분석|통계|보드|히트맵|스코어/.test(n)) return 'dashboard';
  if (/목록|리스트|조회|紐⑸줉/.test(n)) return 'list';
  if (/차트|그래프|추이|예측|리포트|ROI/.test(n)) return 'chart';
  if (/등록|작성|입력|설정|수정|관리/.test(n)) return 'form';
  if (/칸반|보드|타임라인|스프린트/.test(n)) return 'kanban';
  return 'list';
}

const BAR_HEIGHTS = [60, 85, 45, 70, 55, 90, 40, 75];

function PhoneMockup({ screen, color, slug }: { screen: Screen; color: string; slug: string }) {
  const layout = guessLayout(screen.name);
  const alpha = (a: number) => `${color}${Math.round(a * 255).toString(16).padStart(2, '0')}`;
  const [imgFailed, setImgFailed] = React.useState(false);
  const headerBg = `linear-gradient(135deg, ${alpha(0.9)}, ${alpha(0.6)})`;
  return (
    <div className="phone-card">
      <div
        className="phone-frame"
        style={{ borderColor: alpha(0.4) }}
      >
        {/* 상태바 */}
        <div className="phone-status">
          <span>9:41</span>
          <div className="phone-status-icons">
            {/* 배터리 아이콘 (SVG) */}
            <svg width="14" height="8" viewBox="0 0 14 8" fill="none">
              <rect x="0.5" y="0.5" width="11" height="7" rx="1.5" stroke="rgba(255,255,255,0.5)" strokeWidth="1"/>
              <rect x="1.5" y="1.5" width="7" height="5" rx="0.5" fill={color} />
              <path d="M12 2.5v3" stroke="rgba(255,255,255,0.5)" strokeWidth="1" strokeLinecap="round"/>
            </svg>
          </div>
        </div>

        {/* 앱 헤더 */}
        <div className="phone-header" style={{ background: headerBg }}>
          <div className="phone-header-icon" style={{ background: alpha(0.3) }}>
            <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2.5" strokeLinecap="round">
              <rect x="5" y="2" width="14" height="20" rx="2"/>
              <line x1="12" y1="18" x2="12.01" y2="18"/>
            </svg>
          </div>
          <span className="phone-header-title">{screen.name}</span>
          <div className="phone-header-action">
            <svg width="8" height="8" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2.5" strokeLinecap="round">
              <circle cx="12" cy="12" r="1"/><circle cx="19" cy="12" r="1"/><circle cx="5" cy="12" r="1"/>
            </svg>
          </div>
        </div>

        {/* 본문 */}
        <div className="phone-body" style={!imgFailed ? { padding: 0, overflow: 'hidden' } : {}}>
          {!imgFailed && (
            <img
              src={`/screenshots/${slug}.png`}
              alt={screen.name}
              onError={() => setImgFailed(true)}
              style={{ width: '100%', height: '100%', objectFit: 'cover', objectPosition: 'top center', display: 'block' }}
            />
          )}
          {imgFailed && layout === 'dashboard' && (
            <>
              <div className="phone-stat-row">
                <div className="phone-stat">
                  <div className="phone-stat-val" style={{ color }}>24</div>
                  <div className="phone-stat-lbl">진행중</div>
                </div>
                <div className="phone-stat">
                  <div className="phone-stat-val" style={{ color: '#10b981' }}>98%</div>
                  <div className="phone-stat-lbl">완료율</div>
                </div>
              </div>
              <div className="phone-stat-row">
                <div className="phone-stat">
                  <div className="phone-stat-val" style={{ color: '#f59e0b' }}>3</div>
                  <div className="phone-stat-lbl">경보</div>
                </div>
                <div className="phone-stat">
                  <div className="phone-stat-val" style={{ color: '#6366f1' }}>142</div>
                  <div className="phone-stat-lbl">서버</div>
                </div>
              </div>
              <div className="phone-list-item">
                <div className="phone-list-dot" style={{ background: color }} />
                <div className="phone-list-lines">
                  <div className="phone-list-line" style={{ width: '75%' }} />
                  <div className="phone-list-line" style={{ width: '50%', opacity: 0.5 }} />
                </div>
              </div>
            </>
          )}
          {imgFailed && layout === 'chart' && (
            <>
              <div className="phone-stat-row">
                <div className="phone-stat">
                  <div className="phone-stat-val" style={{ color }}>87%</div>
                  <div className="phone-stat-lbl">달성률</div>
                </div>
                <div className="phone-stat">
                  <div className="phone-stat-val" style={{ color: '#10b981' }}>↑12%</div>
                  <div className="phone-stat-lbl">전월비</div>
                </div>
              </div>
              <div className="phone-chart">
                {BAR_HEIGHTS.map((h, i) => (
                  <div
                    key={i}
                    className="phone-bar"
                    style={{
                      height: `${h}%`,
                      background: i === 5 ? color : alpha(0.35 + (i % 3) * 0.1),
                    }}
                  />
                ))}
              </div>
              <div className="phone-list-item">
                <div className="phone-list-dot" style={{ background: '#10b981' }} />
                <div className="phone-list-lines">
                  <div className="phone-list-line" style={{ width: '80%' }} />
                </div>
                <div className="phone-list-badge" style={{ background: alpha(0.2), color }}>AI</div>
              </div>
            </>
          )}
          {imgFailed && (layout === 'list' || layout === 'kanban') && (
            <>
              {[
                { dot: color, w1: '80%', w2: '55%', badge: '완료', bc: '#10b981' },
                { dot: '#f59e0b', w1: '65%', w2: '40%', badge: '진행', bc: '#f59e0b' },
                { dot: '#6366f1', w1: '90%', w2: '70%', badge: '대기', bc: '#6366f1' },
              ].map((row, i) => (
                <div className="phone-list-item" key={i}>
                  <div className="phone-list-dot" style={{ background: row.dot }} />
                  <div className="phone-list-lines">
                    <div className="phone-list-line" style={{ width: row.w1 }} />
                    <div className="phone-list-line" style={{ width: row.w2, opacity: 0.5 }} />
                  </div>
                  <div className="phone-list-badge" style={{ background: `${row.bc}22`, color: row.bc }}>
                    {row.badge}
                  </div>
                </div>
              ))}
            </>
          )}
          {imgFailed && layout === 'form' && (
            <>
              {[70, 100, 85].map((w, i) => (
                <div key={i} style={{
                  background: 'rgba(255,255,255,0.04)',
                  border: '1px solid rgba(255,255,255,0.08)',
                  borderRadius: 6, padding: '5px 8px',
                }}>
                  <div style={{ height: 4, width: '35%', background: alpha(0.5), borderRadius: 2, marginBottom: 4 }} />
                  <div style={{ height: 5, width: `${w}%`, background: 'rgba(255,255,255,0.2)', borderRadius: 2 }} />
                </div>
              ))}
            </>
          )}
        </div>

        {/* 하단 버튼 */}
        <div className="phone-footer">
          <div className="phone-btn" style={{ background: alpha(0.15), border: `1px solid ${alpha(0.3)}`, color }}>
            취소
          </div>
          <div className="phone-btn" style={{ background: headerBg }}>
            확인
          </div>
        </div>
      </div>

      <div className="phone-label">
        <span className="phone-name">{screen.name}</span>
        <span className="phone-type" style={{ color, borderColor: alpha(0.4) }}>
          {TYPE_LABEL[screen.type] || screen.type}
        </span>
      </div>
    </div>
  );
}

export const MobileScreenList: React.FC<MobileScreenListProps> = ({ screens, color, slug }) => {
  if (!screens.length) {
    return <p className="mobile-empty">모바일 앱 화면은 준비 중입니다.</p>;
  }
  return (
    <div className="mobile-screen-list">
      {screens.map((s) => (
        <PhoneMockup key={s.name} screen={s} color={color} slug={slug} />
      ))}
    </div>
  );
};

export default MobileScreenList;
