// screen-applock.jsx — App Lock (refined design)
const { useState: useLockState } = React;

const TIME_OPTIONS = ['3m', '5m', '10m', '15m', '20m'];

const INIT_LOCK_APPS = [
  { id: 'line', name: 'LINE', cat: '通訊', count: 3, timeIdx: 2 },
];

// ─────────────────────────────────────────────────────────────
// LINE App Icon SVG
function LineIcon({ size = 44 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 44 44" fill="none">
      <rect width="44" height="44" rx="10" fill="#06C755"/>
      <g transform="translate(7, 7)">
        {/* LINE speech bubble */}
        <path
          d="M15 3C8.373 3 3 7.477 3 13c0 3.368 1.86 6.322 4.71 8.18-.093.63-.59 3.178-.674 3.63-.097.53.194.524.407.381.168-.113 2.654-1.8 3.73-2.53.897.125 1.82.19 2.827.19 6.627 0 12-4.477 12-10S21.627 3 15 3z"
          fill="white"
        />
        <path
          d="M10.5 11.5h-1v3h1v-3zm4 0h-1v2l-2-2h-1v3h1v-2l2 2h1v-3zm1 0v3h3v-1h-2v-.5h2v-1h-2v-.5h2v-1h-3zm5 0h-1v3h1v-3z"
          fill="#06C755"
          fontSize="8"
        />
      </g>
    </svg>
  );
}

// Better LINE icon using actual LINE logo proportions
function LineIconClean({ size = 44 }) {
  const r = size * 10 / 44;
  return (
    <svg width={size} height={size} viewBox="0 0 44 44" fill="none">
      <rect width="44" height="44" rx={r} fill="#06C755"/>
      {/* Bubble outline */}
      <ellipse cx="22" cy="21" rx="13" ry="11.5" fill="white"/>
      {/* Spike */}
      <path d="M17 30 Q14 34 12 36 Q16 33 19 31" fill="white"/>
      {/* LINE text bars */}
      <rect x="13.5" y="18" width="2.5" height="7" rx="1.2" fill="#06C755"/>
      <rect x="17.5" y="18" width="2.5" height="7" rx="1.2" fill="#06C755"/>
      <rect x="21.5" y="18" width="2.5" height="7" rx="1.2" fill="#06C755"/>
      <rect x="25.5" y="18" width="2.5" height="7" rx="1.2" fill="#06C755"/>
      {/* Cross bars for N and E */}
      <rect x="21.5" y="18" width="7" height="2" rx="1" fill="#06C755"/>
      <rect x="21.5" y="23" width="7" height="2" rx="1" fill="#06C755"/>
    </svg>
  );
}

// ─────────────────────────────────────────────────────────────
// App detail — refined design matching app visual language
function AppLockDetail({ app, onBack, onSave }) {
  const [count, setCount] = useLockState(app.count);
  const [timeIdx, setTimeIdx] = useLockState(app.timeIdx);

  const bg = `radial-gradient(140% 80% at 50% -10%, #16171a 0%, ${W.ink} 55%, ${W.void} 100%)`;

  return (
    <div style={{
      width: '100%', height: '100%', background: bg,
      color: W.textHi, display: 'flex', flexDirection: 'column',
      fontFamily: W.mono,
    }}>
      <WStatusBar time="04:41" />

      {/* Header — back only, no text clutter */}
      <div style={{ display: 'flex', alignItems: 'center', padding: '8px 18px 0' }}>
        <button onClick={onBack} style={{
          width: 36, height: 36, borderRadius: 9999,
          border: '0.5px solid rgba(255,255,255,0.12)',
          background: 'rgba(255,255,255,0.04)', cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center', color: W.text,
        }}>
          <svg width="8" height="14" viewBox="0 0 8 14" fill="none">
            <path d="M7 1L1 7l6 6" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </button>
      </div>

      {/* App identity block */}
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', padding: '28px 0 32px', gap: 12 }}>
        <LineIconClean size={64} />
        <span style={{ fontFamily: W.display, fontSize: 20, fontWeight: 700, letterSpacing: '-0.01em' }}>
          {app.name}
        </span>
      </div>

      {/* Divider */}
      <div style={{ height: '0.5px', background: 'rgba(255,255,255,0.07)', marginBottom: 36 }} />

      <div style={{ flex: 1, overflowY: 'auto', padding: '0 28px 32px' }}>

        {/* Count section */}
        <div style={{ marginBottom: 40 }}>
          <div style={{
            fontFamily: W.display, fontSize: 17, fontWeight: 600,
            color: W.textHi, marginBottom: 24, letterSpacing: '-0.005em', lineHeight: 1.4,
          }}>
            每天理想使用幾次？
          </div>

          <div style={{ display: 'flex', alignItems: 'center', border: '0.5px solid rgba(255,255,255,0.12)', borderRadius: 12 }}>
            <button
              onClick={() => setCount(c => Math.max(0, c - 1))}
              style={{
                width: 56, height: 56, border: 'none', background: 'transparent',
                cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
                color: W.text, fontSize: 24, borderRight: '0.5px solid rgba(255,255,255,0.08)',
              }}
            >−</button>

            <div style={{
              flex: 1, textAlign: 'center',
              fontFamily: W.display, fontSize: 28, fontWeight: 700,
              color: W.textHi, letterSpacing: '-0.02em',
              fontVariantNumeric: 'tabular-nums',
            }}>{count}</div>

            <button
              onClick={() => setCount(c => c + 1)}
              style={{
                width: 56, height: 56, border: 'none', background: 'transparent',
                cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
                color: W.text, fontSize: 24, borderLeft: '0.5px solid rgba(255,255,255,0.08)',
              }}
            >+</button>
          </div>
        </div>

        {/* Time section */}
        <div style={{ marginBottom: 48 }}>
          <div style={{
            fontFamily: W.display, fontSize: 17, fontWeight: 600,
            color: W.textHi, marginBottom: 20, letterSpacing: '-0.005em',
          }}>
            每次封印多久？
          </div>

          <div style={{ display: 'flex', gap: 8 }}>
            {TIME_OPTIONS.map((opt, i) => {
              const on = i === timeIdx;
              return (
                <button
                  key={opt}
                  onClick={() => setTimeIdx(i)}
                  style={{
                    flex: 1, padding: '12px 0', border: 'none', borderRadius: 10,
                    cursor: 'pointer', transition: 'background .18s, color .18s',
                    background: on ? W.accentHi : 'rgba(255,255,255,0.06)',
                    color: on ? W.onAccent : W.text,
                    fontFamily: W.display, fontSize: 14, fontWeight: on ? 700 : 500,
                    letterSpacing: '-0.01em',
                  }}
                >{opt}</button>
              );
            })}
          </div>
        </div>

        {/* Save */}
        <button
          onClick={() => onSave({ ...app, count, timeIdx })}
          style={{
            width: '100%', padding: '17px', borderRadius: 14, border: 'none',
            background: W.accentHi, color: W.onAccent, cursor: 'pointer',
            fontFamily: W.display, fontSize: 17, fontWeight: 700, letterSpacing: '-0.01em',
          }}
        >
          儲存
        </button>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// List screen
function LockListScreen({ apps, onBack, onPickApp, onAddApp }) {
  const bg = `radial-gradient(140% 80% at 50% -10%, #16171a 0%, ${W.ink} 55%, ${W.void} 100%)`;
  return (
    <div style={{
      width: '100%', height: '100%', background: bg,
      color: W.textHi, display: 'flex', flexDirection: 'column', fontFamily: W.mono,
    }}>
      <WStatusBar time="04:41" />

      {/* Header */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '8px 18px 20px' }}>
        <button onClick={onBack} style={{
          width: 36, height: 36, borderRadius: 9999, border: '0.5px solid rgba(255,255,255,0.12)',
          background: 'rgba(255,255,255,0.04)', cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center', color: W.text,
        }}>
          <svg width="8" height="14" viewBox="0 0 8 14" fill="none">
            <path d="M7 1L1 7l6 6" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </button>
        <span style={{ fontFamily: W.display, fontSize: 18, fontWeight: 600, flex: 1, letterSpacing: '-0.01em' }}>
          App 鎖定
        </span>
        <button onClick={onAddApp} style={{
          width: 36, height: 36, borderRadius: 9999, border: '0.5px solid rgba(255,255,255,0.12)',
          background: 'rgba(255,255,255,0.04)', cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center', color: W.text,
        }}>
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
            <line x1="7" y1="2" x2="7" y2="12" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
            <line x1="2" y1="7" x2="12" y2="7" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
          </svg>
        </button>
      </div>

      <div style={{ padding: '0 20px 10px', fontFamily: W.mono, fontSize: 11, color: W.textLo, letterSpacing: '0.1em' }}>
        已鎖定的 APP
      </div>

      <div style={{ flex: 1, overflowY: 'auto', padding: '0 16px 32px' }}>
        <div style={{
          background: 'rgba(255,255,255,0.03)', border: '0.5px solid rgba(255,255,255,0.07)',
          borderRadius: 16, overflow: 'hidden',
        }}>
          {apps.map((app, i) => (
            <button
              key={app.id}
              onClick={() => onPickApp(app)}
              style={{
                width: '100%', display: 'flex', alignItems: 'center', gap: 14,
                padding: '14px 16px', border: 'none', background: 'transparent', cursor: 'pointer',
                borderBottom: i < apps.length - 1 ? '0.5px solid rgba(255,255,255,0.05)' : 'none',
                textAlign: 'left',
              }}
            >
              <LineIconClean size={44} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontFamily: W.display, fontSize: 16, fontWeight: 600, color: W.textHi }}>
                  {app.name}
                </div>
                <div style={{ fontFamily: W.mono, fontSize: 11, color: W.textLo, marginTop: 3, letterSpacing: '0.06em' }}>
                  {app.count}次/天 · {TIME_OPTIONS[app.timeIdx]}/次
                </div>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexShrink: 0 }}>
                <div style={{
                  padding: '4px 10px', borderRadius: 9999,
                  background: 'rgba(196,166,98,0.12)', border: `0.5px solid ${W.accentHi}`,
                  fontFamily: W.mono, fontSize: 11, color: W.accentHi, letterSpacing: '0.06em',
                }}>封印中</div>
                <svg width="7" height="12" viewBox="0 0 7 12" fill="none" style={{ color: W.textXLo }}>
                  <path d="M1 1l5 5-5 5" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
              </div>
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
function ScreenAppLockNew({ onBack }) {
  const [apps, setApps] = useLockState(INIT_LOCK_APPS);
  const [detailApp, setDetailApp] = useLockState(null);

  const handleSave = (updated) => {
    setApps(prev => prev.map(a => a.id === updated.id ? updated : a));
    setDetailApp(null);
  };

  const idx = detailApp ? 1 : 0;

  return (
    <div style={{ width: '100%', height: '100%', position: 'relative', overflow: 'hidden' }}>
      {[
        <LockListScreen
          key="list"
          apps={apps}
          onBack={onBack}
          onPickApp={setDetailApp}
          onAddApp={() => {
            const name = window.prompt('App 名稱：');
            if (name && name.trim()) {
              setApps(prev => [...prev, { id: `app-${Date.now()}`, name: name.trim(), cat: '其他', count: 3, timeIdx: 2 }]);
            }
          }}
        />,
        <AppLockDetail key="detail" app={detailApp || INIT_LOCK_APPS[0]} onBack={() => setDetailApp(null)} onSave={handleSave} />,
      ].map((s, i) => (
        <div key={s.key} style={{
          position: 'absolute', inset: 0,
          transform: `translateX(${(i - idx) * 100}%)`,
          transition: 'transform .35s cubic-bezier(.4,0,.2,1)',
        }}>
          {s}
        </div>
      ))}
    </div>
  );
}

Object.assign(window, { ScreenAppLockNew });
