// phone.jsx — 키토 AI 기록 도우미 앱 목업 (Black & White + Lucide icons)

// ─── Icon (Lucide) ───────────────────────────────────────────
// Lucide UMD exposes each icon as a function under window.lucide.{PascalName}.
// Calling it returns a DOM SVG element. We wrap its outerHTML in a span and
// mount via dangerouslySetInnerHTML — safe because the SVG is static and lives
// inside a span that React fully controls for lifecycle.
function toPascalCase(name) {
  return name.split('-').map(p => p.charAt(0).toUpperCase() + p.slice(1)).join('');
}

function resolveLucide(key) {
  const lib = typeof window !== 'undefined' ? window.lucide : null;
  if (!lib) return null;
  return lib[key] || (lib.icons && lib.icons[key]) || null;
}

function lucideIconMarkup(entry, { size, strokeWidth, color }) {
  // entry may be a function (UMD icon factory) or an IconNode array.
  if (typeof entry === 'function') {
    try {
      const attrs = { width: size, height: size, 'stroke-width': strokeWidth };
      if (color) attrs.stroke = color;
      const node = entry(attrs);
      return node && node.outerHTML ? node.outerHTML : '';
    } catch (e) { return ''; }
  }
  if (Array.isArray(entry)) {
    // Either [svg, attrs, children] OR [[tag, attrs], ...] (children only).
    const isFull = typeof entry[0] === 'string' && entry[0] === 'svg';
    const children = isFull ? (entry[2] || []) : entry;
    const paths = children.map(([tag, attrs]) => {
      const a = Object.keys(attrs || {}).map(k => `${k}="${attrs[k]}"`).join(' ');
      return `<${tag} ${a}/>`;
    }).join('');
    return `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="${color || 'currentColor'}" stroke-width="${strokeWidth}" stroke-linecap="round" stroke-linejoin="round">${paths}</svg>`;
  }
  return '';
}

function Icon({ name, size = 20, strokeWidth = 2, color, style = {} }) {
  const key = toPascalCase(name);
  const entry = resolveLucide(key);
  const spanStyle = Object.assign({ display: 'inline-flex', flexShrink: 0, width: size, height: size, color: color || 'currentColor' }, style);
  if (!entry) {
    // Placeholder reserves the layout slot until Lucide is available.
    return React.createElement('span', { style: spanStyle, 'aria-hidden': 'true' });
  }
  const html = lucideIconMarkup(entry, { size, strokeWidth, color });
  return React.createElement('span', {
    style: spanStyle,
    'aria-hidden': 'true',
    dangerouslySetInnerHTML: { __html: html },
  });
}

function PhoneFrame({ width = 290, height = 600, children, style = {} }) {
  const ink = '#09090b';
  return (
    <div style={{
      width, height,
      borderRadius: 44,
      background: ink,
      padding: 9,
      boxShadow: '0 30px 60px -20px rgba(9,9,11,0.32), 0 8px 20px rgba(9,9,11,0.10), inset 0 0 0 2px rgba(255,255,255,0.06)',
      position: 'relative',
      ...style,
    }}>
      <div style={{
        width: '100%', height: '100%',
        borderRadius: 36,
        background: '#ffffff',
        overflow: 'hidden',
        position: 'relative',
      }}>
        <div style={{
          position: 'absolute', top: 10, left: '50%', transform: 'translateX(-50%)',
          width: 84, height: 24, borderRadius: 16, background: ink, zIndex: 20,
        }} />
        <div style={{
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          padding: '14px 22px 0', fontSize: 12, fontWeight: 600, color: ink,
          position: 'relative', zIndex: 10,
        }}>
          <span style={{ fontVariantNumeric: 'tabular-nums' }}>9:41</span>
          <span style={{ display: 'flex', gap: 4, alignItems: 'center' }}>
            <svg width="14" height="10" viewBox="0 0 14 10" aria-hidden="true"><rect x="0" y="6" width="2.5" height="4" rx="0.5" fill={ink}/><rect x="3.8" y="4" width="2.5" height="6" rx="0.5" fill={ink}/><rect x="7.6" y="2" width="2.5" height="8" rx="0.5" fill={ink}/><rect x="11.4" y="0" width="2.5" height="10" rx="0.5" fill={ink}/></svg>
            <svg width="20" height="10" viewBox="0 0 20 10" aria-hidden="true"><rect x="0.5" y="0.5" width="16" height="9" rx="2" stroke={ink} fill="none"/><rect x="2" y="2" width="13" height="6" rx="1" fill={ink}/><rect x="17" y="3" width="2" height="4" rx="1" fill={ink}/></svg>
          </span>
        </div>
        {children}
      </div>
    </div>
  );
}

function MacroRing({ label, current, target, color, unit, warn }) {
  const pct = Math.min(current / target, 1);
  const r = 22;
  const c = 2 * Math.PI * r;
  return (
    <div style={{ textAlign: 'center' }}>
      <svg width="60" height="60" style={{ transform: 'rotate(-90deg)' }} aria-hidden="true">
        <circle cx="30" cy="30" r={r} stroke="#e4e4e7" strokeWidth="5" fill="none" />
        <circle cx="30" cy="30" r={r} stroke={color} strokeWidth="5" fill="none"
          strokeDasharray={c} strokeDashoffset={c * (1 - pct)} strokeLinecap="round" />
      </svg>
      <div style={{ marginTop: -40, fontSize: 13, fontWeight: 700, letterSpacing: '-0.02em', color: warn && pct > 0.7 ? '#84CC12' : '#09090b', fontVariantNumeric: 'tabular-nums' }}>{current}{unit}</div>
      <div style={{ marginTop: 30, fontSize: 10, color: '#a1a1aa' }}>{label}</div>
      <div style={{ fontSize: 10, color: '#a1a1aa', fontVariantNumeric: 'tabular-nums' }}>/ {target}{unit}</div>
    </div>
  );
}

function PhoneScreenHome() {
  return (
    <div style={{ padding: '40px 18px 0', color: '#09090b' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 18 }}>
        <div>
          <div style={{ fontSize: 10, color: '#a1a1aa', letterSpacing: '0.08em', textTransform: 'uppercase' }}>4월 22일 화요일</div>
          <div style={{ fontSize: 18, fontWeight: 700, marginTop: 4, letterSpacing: '-0.02em' }}>안녕하세요, 지민님</div>
        </div>
        <div style={{ width: 34, height: 34, borderRadius: '50%', background: '#9EF01A', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#09090b', fontSize: 13, fontWeight: 800 }}>지</div>
      </div>

      {/* 식단 기록 카드 */}
      <div style={{
        background: '#09090b',
        color: '#fafafa',
        borderRadius: 18,
        padding: 16,
        marginBottom: 12,
        position: 'relative', overflow: 'hidden',
      }}>
        <div aria-hidden="true" style={{ position: 'absolute', top: -40, right: -40, width: 140, height: 140, borderRadius: '50%', background: 'radial-gradient(circle, rgba(158,240,26,0.32), transparent 70%)' }}/>
        <div style={{ position: 'relative' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
            <div style={{ fontSize: 10, color: '#C7FF63', letterSpacing: '0.1em', textTransform: 'uppercase', fontWeight: 600 }}>식단 기록</div>
            <div style={{ fontSize: 9, padding: '3px 8px', background: '#9EF01A', color: '#09090b', borderRadius: 999, fontWeight: 700, display: 'inline-flex', alignItems: 'center', gap: 4 }}>
              <Icon name="activity" size={10} strokeWidth={2.5} /> 정리 중
            </div>
          </div>
          <div style={{ fontSize: 26, fontWeight: 700, letterSpacing: '-0.03em', fontVariantNumeric: 'tabular-nums' }}>3일차</div>
          <div style={{ fontSize: 11, color: '#e4e4e7', marginTop: 4 }}>오늘 먹은 것을 차곡차곡 정리하고 있어요</div>
        </div>
      </div>

      {/* 매크로 카드 */}
      <div style={{ background: '#f4f4f5', borderRadius: 18, padding: 14, marginBottom: 10 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
          <div style={{ fontSize: 12, fontWeight: 600 }}>오늘 매크로</div>
          <div style={{ fontSize: 10, color: '#a1a1aa' }}>2끼 기록됨</div>
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-around' }}>
          <MacroRing label="탄수" current={14} target={20} color="#9EF01A" unit="g" warn />
          <MacroRing label="지방" current={82} target={120} color="#3f3f46" unit="g" />
          <MacroRing label="단백" current={68} target={90} color="#52525b" unit="g" />
        </div>
      </div>

      <div style={{ display: 'flex', gap: 8 }}>
        <div style={{ flex: 1, background: '#9EF01A', color: '#09090b', padding: '13px 12px', borderRadius: 14, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6, fontSize: 12, fontWeight: 700, boxShadow: '0 6px 14px -4px rgba(158,240,26,0.45)' }}>
          <Icon name="camera" size={14} /> 사진 찍기
        </div>
        <div style={{ flex: 1, background: '#f4f4f5', color: '#09090b', padding: '13px 12px', borderRadius: 14, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6, fontSize: 12, fontWeight: 600 }}>
          <Icon name="pen-line" size={14} /> 글로 쓰기
        </div>
      </div>
    </div>
  );
}

function PhoneScreenChat() {
  return (
    <div style={{ position: 'absolute', inset: 0, padding: '40px 0 0', color: '#09090b', display: 'flex', flexDirection: 'column', boxSizing: 'border-box' }}>
      <div style={{ padding: '8px 18px 12px', borderBottom: '1px solid #e4e4e7', display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{ width: 30, height: 30, borderRadius: '50%', background: '#9EF01A', color: '#09090b', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 800, fontSize: 12 }}>K</div>
        <div>
          <div style={{ fontSize: 12, fontWeight: 700 }}>기록 도우미 케이</div>
          <div style={{ fontSize: 9, color: '#3f3f46', fontWeight: 600, display: 'inline-flex', alignItems: 'center', gap: 4 }}>
            <Icon name="circle-dot" size={9} color="#9EF01A" /> 실시간 피드백 중
          </div>
        </div>
      </div>

      <div style={{ flex: 1, minHeight: 0, padding: '14px 14px', overflow: 'hidden', display: 'flex', flexDirection: 'column', gap: 9 }}>
        <div style={{ alignSelf: 'flex-end', maxWidth: '75%' }}>
          <div style={{
            width: 136, height: 96, borderRadius: '14px 14px 4px 14px',
            position: 'relative', overflow: 'hidden',
            backgroundImage: 'url(assets/chat-meal.jpg)',
            backgroundSize: 'cover', backgroundPosition: 'center',
          }}>
            <div aria-hidden="true" style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg, rgba(0,0,0,0) 55%, rgba(0,0,0,0.45) 100%)' }}/>
            <div style={{ position: 'absolute', bottom: 6, right: 10, fontSize: 9, color: 'rgba(255,255,255,0.95)', fontFamily: 'monospace', fontVariantNumeric: 'tabular-nums' }}>점심 · 12:34</div>
          </div>
        </div>

        <div style={{ alignSelf: 'flex-start', background: '#f4f4f5', borderRadius: '4px 14px 14px 14px', padding: '10px 12px', fontSize: 11, maxWidth: '82%' }}>
          <div style={{ fontSize: 9, color: '#a1a1aa', marginBottom: 6, letterSpacing: '0.04em' }}>식단 메모 정리</div>
          <div style={{ fontWeight: 600, marginBottom: 6 }}>닭고기 풋콩 볶음 + 잡곡밥 + 콩나물 계란국</div>
          <div style={{ display: 'flex', gap: 5, flexWrap: 'wrap' }}>
            <span style={{ fontSize: 9, padding: '2px 7px', background: '#ffffff', border: '1px solid #e4e4e7', borderRadius: 999, fontVariantNumeric: 'tabular-nums' }}>탄 32g</span>
            <span style={{ fontSize: 9, padding: '2px 7px', background: '#ffffff', border: '1px solid #e4e4e7', borderRadius: 999, fontVariantNumeric: 'tabular-nums' }}>지 14g</span>
            <span style={{ fontSize: 9, padding: '2px 7px', background: '#ffffff', border: '1px solid #e4e4e7', borderRadius: 999, fontVariantNumeric: 'tabular-nums' }}>단 38g</span>
          </div>
        </div>

        <div style={{ alignSelf: 'flex-start', background: '#9EF01A', color: '#09090b', borderRadius: '14px 14px 14px 4px', padding: '10px 12px', fontSize: 11.5, maxWidth: '82%', lineHeight: 1.5, fontWeight: 500, display: 'flex', alignItems: 'flex-start', gap: 6 }}>
          <Icon name="sparkles" size={14} style={{ marginTop: 1 }} />
          <span>잡곡밥 한 공기가 오늘 탄수의 대부분을 차지했어요. 다음 끼는 밥을 줄이거나 쌈채소로 바꿔보면 흐름이 가벼워질 거예요.</span>
        </div>

        <div style={{ alignSelf: 'flex-start', background: '#f4f4f5', borderRadius: 14, padding: '8px 12px' }}>
          <span className="typing-dot"/><span className="typing-dot"/><span className="typing-dot"/>
        </div>
      </div>

      <div style={{ padding: '8px 14px 16px', borderTop: '1px solid #e4e4e7', display: 'flex', gap: 8, alignItems: 'center' }}>
        <div style={{ width: 30, height: 30, borderRadius: '50%', background: '#9EF01A', color: '#09090b', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Icon name="plus" size={14} />
        </div>
        <div style={{ flex: 1, background: '#f4f4f5', borderRadius: 999, padding: '8px 14px', fontSize: 10, color: '#a1a1aa' }}>질문하거나, 먹은 것을 찍어 올려요</div>
      </div>
    </div>
  );
}

function PhoneScreenLog() {
  const meals = [
    { time: '아침 · 08:12', name: '버터 커피 + 아보카도', carb: 3, fat: 32, prot: 4, icon: 'coffee', tint: '#e4e4e7' },
    { time: '점심 · 12:34', name: '삼겹살 쌈 정식', carb: 4, fat: 58, prot: 42, icon: 'beef', tint: '#a1a1aa' },
    { time: '간식 · 15:20', name: '마카다미아 한 줌', carb: 2, fat: 22, prot: 3, icon: 'nut', tint: '#d4d4d8' },
  ];
  return (
    <div style={{ padding: '40px 18px 0', color: '#09090b' }}>
      <div style={{ fontSize: 10, color: '#a1a1aa', letterSpacing: '0.08em', textTransform: 'uppercase' }}>오늘의 기록</div>
      <div style={{ fontSize: 20, fontWeight: 700, marginTop: 4, marginBottom: 4, letterSpacing: '-0.02em', fontVariantNumeric: 'tabular-nums' }}>탄수 <span style={{ color: '#84CC12' }}>9g</span> <span style={{ color: '#a1a1aa', fontWeight: 500 }}>/ 20g</span></div>
      <div style={{ height: 6, background: '#e4e4e7', borderRadius: 999, marginBottom: 18, overflow: 'hidden' }}>
        <div style={{ width: '45%', height: '100%', background: '#9EF01A', borderRadius: 999 }}/>
      </div>

      {meals.map((m, i) => (
        <div key={i} style={{ display: 'flex', gap: 12, padding: '12px 0', borderBottom: i < meals.length - 1 ? '1px solid #e4e4e7' : 'none', alignItems: 'center' }}>
          <div style={{
            width: 42, height: 42, borderRadius: 12,
            background: `radial-gradient(circle at 30% 30%, ${m.tint}, #52525b 90%)`,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: '#FFFFFF',
            flexShrink: 0,
          }}>
            <Icon name={m.icon} size={20} />
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 10, color: '#a1a1aa', fontVariantNumeric: 'tabular-nums' }}>{m.time}</div>
            <div style={{ fontSize: 12, fontWeight: 600, marginTop: 2, letterSpacing: '-0.01em' }}>{m.name}</div>
            <div style={{ display: 'flex', gap: 8, marginTop: 5, fontSize: 10, color: '#52525b', fontVariantNumeric: 'tabular-nums' }}>
              <span>탄 {m.carb}g</span><span>·</span><span>지 {m.fat}g</span><span>·</span><span>단 {m.prot}g</span>
            </div>
          </div>
          <Icon name="check" size={14} color="#8FA65A" />
        </div>
      ))}
    </div>
  );
}

Object.assign(window, { Icon, PhoneFrame, PhoneScreenHome, PhoneScreenChat, PhoneScreenLog, MacroRing });
