const { useState, useEffect, useMemo } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "stage": "intro",
  "hue": "orange",
  "camp": "new"
}/*EDITMODE-END*/;

const CAMPAIGN_LIST = [
  { name: 'Loomly — Reddit + PH Launch', brand: 'Loomly', channels: 'Reddit · Product Hunt', staff: 6, status: 'Running', created: 'Today' },
  { name: 'Finch — Dev-tools seeding', brand: 'Finch', channels: 'Reddit', staff: 4, status: 'Running', created: 'Mar 29' },
  { name: 'Loomly — v2 launch push', brand: 'Loomly', channels: 'Product Hunt', staff: 3, status: 'Paused', created: 'Mar 14' },
  { name: 'Finch — Founder AMA series', brand: 'Finch', channels: 'Reddit · Twitter', staff: 5, status: 'Completed', created: 'Feb 22' },
];

function initialChatState(tweaks) {
  const base = {
    campaignName: 'New campaign',
    messages: [],
    brand: null,
    plans: [],
    mode: null,
    selectedSubs: [],
    linkedAccounts: 0,
    step: STEPS.INTRO,
  };
  if (tweaks.camp === 'second') {
    base.brand = BRAND;
    base.campaignName = 'Loomly — v2 launch';
  }
  if (tweaks.stage === 'plan') {
    base.brand = BRAND;
    base.plans = ['reddit', 'producthunt'];
    base.mode = 'checkpoint';
    base.selectedSubs = SUBREDDITS.map(s => s.name);
    base.step = STEPS.SUBREDDIT_PICK;
    base.campaignName = 'Loomly — Reddit + PH Launch';
  } else if (tweaks.stage === 'active') {
    base.brand = BRAND;
    base.plans = ['reddit', 'producthunt'];
    base.mode = 'checkpoint';
    base.selectedSubs = SUBREDDITS.map(s => s.name);
    base.linkedAccounts = 1;
    base.step = STEPS.ACTIVE;
    base.campaignName = 'Loomly — Reddit + PH Launch';
  }
  return base;
}

function App() {
  const [tweaks, setTweaks] = useState(TWEAK_DEFAULTS);
  const [tweaksOpen, setTweaksOpen] = useState(false);
  const [page, setPage] = useState('create');
  const [campaignTab, setCampaignTab] = useState('chat');
  const [chat, setChat] = useState(() => initialChatState(TWEAK_DEFAULTS));
  const [stepModal, setStepModal] = useState(null);
  const [contentEditIdx, setContentEditIdx] = useState(null);
  const [toasts, setToasts] = useState([]);

  useEffect(() => {
    const hues = { orange: 45, plum: 320, sage: 160, slate: 255 };
    const h = hues[tweaks.hue] || 45;
    document.documentElement.style.setProperty('--accent', `oklch(0.68 0.14 ${h})`);
    document.documentElement.style.setProperty('--accent-hover', `oklch(0.62 0.15 ${h})`);
    document.documentElement.style.setProperty('--accent-soft', `oklch(0.94 0.04 ${h})`);
    document.documentElement.style.setProperty('--accent-fg', `oklch(0.35 0.1 ${h})`);
  }, [tweaks.hue]);

  useEffect(() => {
    setChat(initialChatState(tweaks));
    setCampaignTab(tweaks.stage === 'active' ? 'activity' : 'chat');
    setPage('create');
  }, [tweaks.stage, tweaks.camp]);

  // Auto-toast on entering active state
  useEffect(() => {
    if (chat.step === STEPS.ACTIVE) {
      const t1 = setTimeout(() => {
        setToasts(ts => [...ts, { id: Date.now(), sev: 'warn', icon: 'Warn',
          title: 'Account flagged', body: 'u/foldernauts held by r/Entrepreneur mod filter. Review the thread in chat.' }]);
      }, 900);
      const t2 = setTimeout(() => {
        setToasts(ts => [...ts, { id: Date.now()+1, sev: 'success', icon: 'Spark',
          title: 'u/markdown_mike is trending', body: '47 upvotes in 2h on r/NoteTaking warm-up post.' }]);
      }, 2400);
      const t3 = setTimeout(() => {
        setToasts(ts => [...ts, { id: Date.now()+2, sev: 'info', icon: 'Eye',
          title: 'Day 5 draft ready to review', body: 'Ships tomorrow 8:30 AM. Tap to open.' }]);
      }, 4000);
      return () => { clearTimeout(t1); clearTimeout(t2); clearTimeout(t3); };
    }
  }, [chat.step]);

  useEffect(() => {
    const handler = (e) => {
      if (e.data?.type === '__activate_edit_mode') setTweaksOpen(true);
      if (e.data?.type === '__deactivate_edit_mode') setTweaksOpen(false);
    };
    window.addEventListener('message', handler);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', handler);
  }, []);

  const setTweaksAndPersist = (next) => {
    setTweaks(next);
    window.parent.postMessage({ type: '__edit_mode_set_keys', edits: next }, '*');
  };

  const actions = useMemo(() => ({
    submitBrand: (b) => setChat(c => ({ ...c, brand: { ...BRAND, ...b }, step: STEPS.BRAND_DONE, campaignName: b.name + ' — campaign 1' })),
    setPlans: (plans) => setChat(c => ({ ...c, plans, step: c.step === STEPS.BRAND_DONE ? STEPS.PLAN_PICK : c.step })),
    confirmPlans: () => setChat(c => ({ ...c, step: STEPS.PLAN_DONE })),
    setMode: (mode) => setChat(c => ({ ...c, mode, step: c.step === STEPS.PLAN_DONE ? STEPS.MODE_PICK : c.step })),
    confirmMode: () => setChat(c => ({ ...c, step: STEPS.MODE_DONE })),
    startResearch: () => setChat(c => ({ ...c, step: STEPS.RESEARCHING })),
    finishResearching: () => setChat(c => ({ ...c, step: STEPS.SUBREDDIT_PICK, selectedSubs: SUBREDDITS.map(s => s.name) })),
    toggleSub: (name) => setChat(c => ({ ...c, selectedSubs: c.selectedSubs.includes(name) ? c.selectedSubs.filter(x=>x!==name) : [...c.selectedSubs, name] })),
    confirmSubs: () => setChat(c => ({ ...c, step: STEPS.STAFF })),
    toggleLinkedAccount: () => setChat(c => ({ ...c, linkedAccounts: c.linkedAccounts > 0 ? 0 : 1 })),
    confirmStaff: () => setChat(c => ({ ...c, step: STEPS.CALENDAR })),
    confirmCalendar: () => setChat(c => ({ ...c, step: STEPS.CONFIRM })),
    launch: () => { setChat(c => ({ ...c, step: STEPS.ACTIVE })); setCampaignTab('activity'); },
    userMessage: (txt) => setChat(c => ({ ...c, messages: [...c.messages, { role: 'user', text: txt }] })),
  }), []);

  const openAssets = () => setPage('assets');
  const openContentEditor = (idx) => setContentEditIdx(idx);
  const openStepModal = (key) => setStepModal(key);
  const closeStepModal = () => setStepModal(null);
  const dismissToast = (id) => setToasts(ts => ts.filter(t => t.id !== id));

  const renderPage = () => {
    switch (page) {
      case 'dashboard': return <Dashboard onNav={setPage} />;
      case 'create': return (
        <>
          <ChatView state={chat} actions={actions} campaignTab={campaignTab} setCampaignTab={setCampaignTab}
            openContentEditor={openContentEditor} openStepModal={openStepModal} />
          <CampaignPanel state={chat} onOpenAssets={openAssets} openStepModal={openStepModal} />
        </>
      );
      case 'campaigns': return <CampaignsList campaigns={CAMPAIGN_LIST} onOpen={() => setPage('create')} onNew={() => setPage('create')} />;
      case 'assets': return <BrandAssetsPage brand={chat.brand || BRAND} />;
      case 'settings': return <StubPage title="Account" subtitle="Billing, team, integrations" />;
      default: return null;
    }
  };

  const showRightRail = page === 'create';

  return (
    <div className="app" data-no-right={!showRightRail}>
      <Sidebar page={page} setPage={setPage} campaigns={CAMPAIGN_LIST} />
      {renderPage()}
      {tweaksOpen && <TweaksPanel tweaks={tweaks} setTweaks={setTweaksAndPersist} onClose={() => {
        setTweaksOpen(false);
        window.parent.postMessage({ type: '__edit_mode_toggle', active: false }, '*');
      }} />}
      {stepModal === 'budget' && <BudgetStepModal state={chat} actions={actions} onClose={closeStepModal} />}
      {stepModal === 'subs' && <SubredditsStepModal state={chat} actions={actions} onClose={closeStepModal} />}
      {stepModal === 'staff' && <StaffStepModal state={chat} actions={actions} onClose={closeStepModal} />}
      {stepModal === 'calendar' && <CalendarStepModal onClose={closeStepModal} />}
      {stepModal === 'content' && <ContentEditModal index={0} onClose={closeStepModal} onSave={()=>{}} />}
      {contentEditIdx !== null && <ContentEditModal index={contentEditIdx} onClose={() => setContentEditIdx(null)} onSave={()=>{}} />}

      <div className="toast-stack">
        {toasts.map(t => <Toast key={t.id} toast={t} onDismiss={() => dismissToast(t.id)} />)}
      </div>
    </div>
  );
}

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