// app.jsx — main shell + bottom nav

function BottomNav({ tab, setTab }) {
  const tabs = [
    { id: 'today', label: 'Hari Ini', icon: (
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
        <rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/>
        <circle cx="12" cy="16" r="1.5" fill="currentColor"/>
      </svg>
    )},
    { id: 'history', label: 'Riwayat', icon: (
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
        <path d="M3 12a9 9 0 1 0 3-6.7L3 8"/><polyline points="3 3 3 8 8 8"/><polyline points="12 7 12 12 15 14"/>
      </svg>
    )},
    { id: 'habits', label: 'Habit', icon: (
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
        <line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/>
        <circle cx="4" cy="6" r="1.5" fill="currentColor"/><circle cx="4" cy="12" r="1.5" fill="currentColor"/><circle cx="4" cy="18" r="1.5" fill="currentColor"/>
      </svg>
    )},
  ];
  return (
    <nav className="bottom-nav">
      {tabs.map(t => (
        <button key={t.id} className={`nav-item ${tab === t.id ? 'is-active' : ''}`}
          onClick={() => setTab(t.id)}>
          <span className="nav-icon">{t.icon}</span>
          <span className="nav-label">{t.label}</span>
        </button>
      ))}
    </nav>
  );
}

const THEMES = {
  linen: {
    name: 'Linen',
    '--bg': '#EFEDE6',
    '--surface': '#F8F6F0',
    '--surface-2': '#E3DFD3',
    '--ink': '#1C1B17',
    '--muted': '#6B6960',
    '--muted-2': '#9A968B',
    '--border': '#DAD5C5',
    '--border-strong': '#BDB7A4',
    '--accent': '#2C6E6B',
    '--accent-soft': '#DCE8E6',
  },
  mocha: {
    name: 'Mocha',
    '--bg': '#E9DFD0',
    '--surface': '#F4EBDB',
    '--surface-2': '#DBCEB7',
    '--ink': '#2A1F16',
    '--muted': '#7A6650',
    '--muted-2': '#A89479',
    '--border': '#D2C2A4',
    '--border-strong': '#B89F7A',
    '--accent': '#A14E2D',
    '--accent-soft': '#EFDCCE',
  },
  slate: {
    name: 'Slate',
    '--bg': '#E9EBF0',
    '--surface': '#F3F4F8',
    '--surface-2': '#DBDFE6',
    '--ink': '#171922',
    '--muted': '#5B5F6A',
    '--muted-2': '#959AA4',
    '--border': '#D1D5DD',
    '--border-strong': '#AEB4BF',
    '--accent': '#3A4DC9',
    '--accent-soft': '#DDE0F5',
  },
  carbon: {
    name: 'Carbon',
    '--bg': '#161719',
    '--surface': '#1F2124',
    '--surface-2': '#2A2D32',
    '--ink': '#EAE7DF',
    '--muted': '#8E8C85',
    '--muted-2': '#5F5D58',
    '--border': '#2F3236',
    '--border-strong': '#454850',
    '--accent': '#D69C3C',
    '--accent-soft': '#3A2E18',
  },
};

function applyTheme(themeId, density) {
  const root = document.documentElement;
  const theme = THEMES[themeId] || THEMES.linen;
  for (const [k, v] of Object.entries(theme)) {
    if (k.startsWith('--')) root.style.setProperty(k, v);
  }
  root.style.setProperty('--density', density === 'compact' ? '0.85' : '1');
}

function TweaksPanel({ tweaks, setTweak, onClose }) {
  return (
    <div className="tweaks-panel">
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
        <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 500, margin: 0, color: 'var(--ink)' }}>Tweaks</h3>
        <button className="icon-btn-sm" onClick={onClose} aria-label="tutup">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
        </button>
      </div>

      <div className="tweak-section">
        <div className="tweak-label">Tema</div>
        <div className="theme-swatches">
          {Object.entries(THEMES).map(([id, t]) => (
            <button key={id}
              className={`theme-swatch ${tweaks.theme === id ? 'is-active' : ''}`}
              onClick={() => setTweak('theme', id)}>
              <div className="theme-swatch-preview" style={{ background: t['--bg'] }}>
                <div style={{ background: t['--surface'], height: '50%', borderRadius: '6px 6px 0 0' }}/>
                <div style={{ background: t['--accent'], width: 16, height: 16, borderRadius: 8, position: 'absolute', bottom: 6, right: 6 }}/>
              </div>
              <span>{t.name}</span>
            </button>
          ))}
        </div>
      </div>

      <div className="tweak-section">
        <div className="tweak-label">Tampilan Penyempurna</div>
        <div className="seg">
          {[
            { id: 'always', label: 'Selalu Tampil' },
            { id: 'auto', label: 'Setelah Utama' },
          ].map(o => (
            <button key={o.id}
              className={`seg-btn ${tweaks.addonsMode === o.id ? 'is-active' : ''}`}
              onClick={() => setTweak('addonsMode', o.id)}>{o.label}</button>
          ))}
        </div>
      </div>

      <div className="tweak-section">
        <div className="tweak-label">Kerapatan</div>
        <div className="seg">
          {[
            { id: 'comfort', label: 'Nyaman' },
            { id: 'compact', label: 'Padat' },
          ].map(o => (
            <button key={o.id}
              className={`seg-btn ${tweaks.density === o.id ? 'is-active' : ''}`}
              onClick={() => setTweak('density', o.id)}>{o.label}</button>
          ))}
        </div>
      </div>
    </div>
  );
}

const DEFAULT_TWEAKS = /*EDITMODE-BEGIN*/{
  "theme": "linen",
  "addonsMode": "always",
  "density": "comfort"
}/*EDITMODE-END*/;

function App() {
  const [state, setState] = React.useState(() => loadState());
  const [tab, setTab] = React.useState('today');
  const [date, setDate] = React.useState(new Date());
  const [tweaks, setTweaks] = React.useState(() => {
    try {
      const saved = { ...DEFAULT_TWEAKS, ...JSON.parse(localStorage.getItem('habit-ican-tweaks') || '{}') };
      // migrate stale theme ids
      if (!THEMES[saved.theme]) saved.theme = DEFAULT_TWEAKS.theme;
      return saved;
    } catch { return DEFAULT_TWEAKS; }
  });
  const [tweaksOpen, setTweaksOpen] = React.useState(false);

  // persist state
  React.useEffect(() => { saveState(state); }, [state]);
  React.useEffect(() => {
    try { localStorage.setItem('habit-ican-tweaks', JSON.stringify(tweaks)); } catch {}
    applyTheme(tweaks.theme, tweaks.density);
    document.body.setAttribute('data-addons-mode', tweaks.addonsMode);
  }, [tweaks]);

  // edit-mode protocol for tweaks
  React.useEffect(() => {
    const onMsg = (e) => {
      if (e.data?.type === '__activate_edit_mode') setTweaksOpen(true);
      else if (e.data?.type === '__deactivate_edit_mode') setTweaksOpen(false);
    };
    window.addEventListener('message', onMsg);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', onMsg);
  }, []);

  const setTweak = (key, value) => {
    setTweaks(t => {
      const next = { ...t, [key]: value };
      window.parent.postMessage({ type: '__edit_mode_set_keys', edits: { [key]: value } }, '*');
      return next;
    });
  };

  return (
    <div className="app-shell" data-screen-label="Habit Ican">
      <main className="screen">
        {tab === 'today' && <TodayScreen state={state} setState={setState} date={date} setDate={setDate}/>}
        {tab === 'history' && <HistoryScreen state={state}/>}
        {tab === 'habits' && <HabitsScreen state={state} setState={setState}/>}
      </main>
      <BottomNav tab={tab} setTab={setTab}/>
      {tweaksOpen && (
        <div className="sheet-backdrop" onClick={() => {
          setTweaksOpen(false);
          window.parent.postMessage({ type: '__edit_mode_dismissed' }, '*');
        }}>
          <div onClick={(e) => e.stopPropagation()}>
            <TweaksPanel tweaks={tweaks} setTweak={setTweak} onClose={() => {
              setTweaksOpen(false);
              window.parent.postMessage({ type: '__edit_mode_dismissed' }, '*');
            }}/>
          </div>
        </div>
      )}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
