// components/rinpo-phone.jsx — RINPO Phone OS (multi-screen)

function RinpoPhoneOS({ overlay }) {
  const store = useStore();
  const route = useRoute();
  const assets = window.RinpoAssets;
  const apps = window.RinpoPhoneApps || [];
  const [tipIdx, setTipIdx] = React.useState(0);

  const tab = store.state.phoneTab || route.query.tab || 'apps';
  const detailId = store.state.phoneDetailApp;

  const closePhone = function () {
    if (overlay || (store.isPhoneDesktop() && store.state.phoneOpen)) {
      store.closePhoneOverlay();
    } else {
      HAPRouter.nav('#/');
    }
  };

  React.useEffect(function () {
    if (route.query.tab && route.query.tab !== store.state.phoneTab) {
      store.setPhoneTab(route.query.tab);
    }
  }, [route.query.tab]);

  React.useEffect(function () {
    const t = setInterval(function () { setTipIdx(function (i) { return (i + 1) % assets.tips.length; }); }, 8000);
    return function () { clearInterval(t); };
  }, []);

  const dateStr = new Date().toLocaleDateString('en-IN', {
    weekday: 'long', day: 'numeric', month: 'long',
  }).toUpperCase();

  const user = store.state.user;
  const greeting = user
    ? 'Great to see you again, ' + (user.name || 'friend') + '! Explore the garden store.'
    : 'Tap an app — or chat with RINPO.';

  const setTab = function (t) {
    store.setPhoneTab(t);
    HAPRouter.nav('#/phone?tab=' + t);
  };

  const badgeFor = function (app) {
    if (app.badgeFrom === 'cart') return store.cartCount() || null;
    if (app.badgeFrom === 'orders') return store.notificationCount() || null;
    return null;
  };

  const openApp = function (app) {
    if (app.action === 'chat') { setTab('chat'); return; }
    store.setPhoneDetail(app.id);
  };

  const detailApp = detailId ? window.RinpoPhoneApps.byId(detailId) : null;

  return (
    <div className="rinpo-phone rinpo-phone-os">
      {tab === 'apps' && !detailApp && (
        <header className="rinpo-phone__greeting-card">
          <div className="rinpo-phone__greeting-top">
            <div className="rinpo-phone__date">{dateStr}</div>
            <button type="button" className="rinpo-phone__greeting-close" onClick={closePhone} aria-label="Close RINADS PHONE">
              <Icon name="close" size={16} />
            </button>
          </div>
          <div className="rinpo-phone__intro">
            <RinpoAvatarImage variant="compact" showPill={false} />
            <p className="rinpo-phone__intro-text">{greeting}</p>
          </div>
          <div className="rinpo-phone__powered">
            {(assets.brand && assets.brand.intelligence) || 'RINPO Intelligence OS'}
            {' · powered by '}
            {(assets.brand && assets.brand.poweredBy) || 'RINADS TECHNOLOGIES'}
          </div>
        </header>
      )}

      {tab === 'apps' && !detailApp && (
        <>
          <div className="rinpo-phone__tip">
            <span className="rinpo-phone__tip-icon"><Icon name="spark" size={16} /></span>
            <span><strong>Did you know?</strong> {assets.tips[tipIdx]}</span>
          </div>
          <nav className="rinpo-phone__grid" aria-label="Ambady store apps">
            {apps.map(function (app) {
              const badge = badgeFor(app);
              return (
                <button key={app.id} type="button" className="rinpo-phone__tile" onClick={() => openApp(app)}>
                  <span className="rinpo-phone__tile-icon">
                    {app.icon === 'rinpo' ? (
                      <RinpoAvatarImage variant="compact" showPill={false} />
                    ) : (
                      <Icon name={app.icon} size={20} />
                    )}
                  </span>
                  <span className="rinpo-phone__tile-label">{app.label}</span>
                  {badge ? <span className="rinpo-phone__tile-badge">{badge}</span> : null}
                </button>
              );
            })}
          </nav>
        </>
      )}

      {tab === 'apps' && detailApp && (
        <RinpoPhoneAppDetail
          app={detailApp}
          onBack={() => store.clearPhoneDetail()}
          onAskRinpo={(a) => {
            store.openPhoneTab('chat', 'Tell me about ' + a.label.toLowerCase());
            HAPRouter.nav('#/phone?tab=chat');
          }}
          onOpenStore={(href) => HAPRouter.nav(href)}
        />
      )}

      {tab === 'chat' && <RinpoPhoneChat />}

      {tab === 'quick' && <RinpoPhoneQuickShop />}

      {tab === 'notifications' && <RinpoPhoneNotifications />}

      {tab === 'profile' && <RinpoPhoneProfile />}

      <footer className="rinpo-os-nav" aria-label="RINADS PHONE navigation">
        {[
          ['chat', 'message', 'Chat'],
          ['apps', 'apps', 'Apps'],
          ['quick', 'spark', 'Quick Actions'],
          ['notifications', 'bell', 'Notifications'],
          ['profile', 'user', 'Profile'],
        ].map(function (row) {
          const id = row[0];
          const on = tab === id || (id === 'apps' && (tab === 'apps' || detailApp));
          const badge = id === 'notifications' ? store.notificationCount() : 0;
          return (
            <button
              key={id}
              type="button"
              className={'rinpo-os-nav__btn' + (on ? ' on' : '') + (id === 'apps' && on ? ' rinpo-os-nav__btn--apps' : '')}
              onClick={() => { store.clearPhoneDetail(); setTab(id); }}
            >
              <span className={'rinpo-os-nav__icon-wrap' + (id === 'apps' ? ' rinpo-os-nav__icon-wrap--apps' : '')}>
                <Icon name={row[1]} size={20} />
                {badge > 0 && <span className="rinpo-os-nav__badge">{badge}</span>}
              </span>
              {row[2]}
            </button>
          );
        })}
      </footer>
    </div>
  );
}

function RinpoPhoneQuickShop() {
  const store = useStore();
  const recent = store.recentProducts();
  const forYou = window.CustomerPersonalization
    ? window.CustomerPersonalization.forYou(8).products
    : [];
  const list = recent.length ? recent : forYou.length ? forYou : HAP.productsInCategory('pebbles').slice(0, 6);

  return (
    <div className="rinpo-os-quick">
      <h2 className="rinpo-os-quick__title">Quick Actions</h2>
      <p className="rinpo-os-quick__sub">Recently viewed and picks for you</p>
      <div className="rinpo-os-quick__scroll">
        {list.map(function (p) {
          return (
            <div key={p.id} className="rinpo-os-quick__card">
              <a href={'#/products/' + p.slug}><img src={p.image} alt={p.name} /></a>
              <div className="rinpo-os-quick__name">{p.name}</div>
              <div className="rinpo-os-quick__price">{HAP.formatPrice(window.CustomerCommerce.unitPrice(p.price, p.variants[0]))}</div>
              <button type="button" className="rinpo-os-quick__add" onClick={() => store.addToCart(p.id, p.variants[0], 1)}>+ Add</button>
            </div>
          );
        })}
      </div>
      <a href="#/collections/pebbles" className="rinpo-os-detail__secondary" style={{ margin: '16px' }}>Browse all pebbles</a>
    </div>
  );
}

function RinpoPhoneNotifications() {
  const store = useStore();
  const user = store.state.user;
  const orders = global.APG ? global.APG.getOrders() : store.state.orders;
  const mine = user
    ? orders.filter(function (o) { return o.details && o.details.email === user.email; })
    : orders.slice(0, 8);

  if (!mine.length) {
    return (
      <div className="rinpo-os-notif rinpo-os-notif--empty">
        <Icon name="bell" size={28} />
        <p>No alerts yet — place an order to get updates.</p>
        <a href="#/collections/pebbles">Shop pebbles</a>
      </div>
    );
  }

  return (
    <div className="rinpo-os-notif">
      {mine.map(function (o) {
        return (
          <a key={o.id} href={'#/track?o=' + encodeURIComponent(o.id)} className="rinpo-os-notif__row">
            <Icon name="package" size={18} />
            <div>
              <div className="rinpo-os-notif__title">Order {o.id}</div>
              <div className="rinpo-os-notif__meta">Status: {o.status} · {HAP.formatPrice(o.total)}</div>
            </div>
          </a>
        );
      })}
    </div>
  );
}

window.RinpoPhoneOS = RinpoPhoneOS;
window.RinpoPhoneShell = function RinpoPhoneShell({ overlay }) {
  return (
    <RinpoPhoneFrame>
      <RinpoPhoneOS overlay={overlay} />
    </RinpoPhoneFrame>
  );
};
