// screen-integrations.jsx — Integrations grid: toggle, configure drawer
// Exports: IntegrationsScreen

const INTEGRATIONS = [
  { id: 'judgeme',  name: 'Judge.me',    cat: 'Reviews',   phase: 'MVP',     enabled: true,  icon: 'star',          desc: 'Display star ratings and reviews on every product page. Increases conversion by up to 18%.' },
  { id: 'klaviyo',  name: 'Klaviyo',     cat: 'Marketing', phase: 'Phase 2', enabled: false, icon: 'mail',          desc: 'Sync app events to Klaviyo flows. Trigger email & SMS based on app behavior.' },
  { id: 'smile',    name: 'Smile.io',    cat: 'Loyalty',   phase: 'Phase 2', enabled: false, icon: 'gift',          desc: 'Show loyalty points balance in the app. Let customers redeem at checkout.' },
  { id: 'loox',     name: 'Loox',        cat: 'Reviews',   phase: 'Phase 2', enabled: false, icon: 'camera',        desc: 'Photo and video reviews from real customers, displayed natively in the app.' },
  { id: 'omnisend', name: 'Omnisend',    cat: 'Marketing', phase: 'Phase 2', enabled: false, icon: 'send',          desc: 'Connect app events to Omnisend automation workflows.' },
  { id: 'recharge', name: 'Recharge',    cat: 'Subscriptions', phase: 'Phase 2', enabled: false, icon: 'repeat',   desc: 'Let customers manage their subscriptions directly from the app.' },
  { id: 'yotpo',    name: 'Yotpo',       cat: 'Reviews',   phase: 'Phase 2', enabled: false, icon: 'message-square', desc: 'UGC and reviews platform. Sync ratings and loyalty points.' },
  { id: 'gorgias',  name: 'Gorgias',     cat: 'Support',   phase: 'Phase 2', enabled: false, icon: 'headphones',    desc: 'In-app customer support chat powered by Gorgias.' },
  { id: 'tidio',    name: 'Tidio',       cat: 'Support',   phase: 'Phase 2', enabled: false, icon: 'message-circle', desc: 'Live chat and chatbot support inside the app.' },
  { id: 'bold',     name: 'Bold Upsell', cat: 'Upsell',    phase: 'Phase 2', enabled: false, icon: 'trending-up',   desc: 'Show post-purchase upsell and cross-sell offers in the checkout flow.' },
];

const ConfigureDrawer = ({ integration, onClose }) => {
  const [reviewCount, setReviewCount] = React.useState('3');
  const [placement, setPlacement] = React.useState('below_description');
  const [showRating, setShowRating] = React.useState(true);
  const [saved, setSaved] = React.useState(false);

  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 200, display: 'flex', justifyContent: 'flex-end' }}>
      <div onClick={onClose} style={{ position: 'absolute', inset: 0, background: 'rgba(26,26,26,0.3)' }}></div>
      <div style={{ position: 'relative', width: 380, background: 'var(--white)', height: '100%', boxShadow: 'var(--shadow-modal)', display: 'flex', flexDirection: 'column', animation: 'slideInRight 320ms var(--ease)' }}>
        <div style={{ padding: '20px 24px', borderBottom: '1px solid var(--hairline)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div>
            <div style={{ fontSize: 15, fontWeight: 600, color: 'var(--fg-1)' }}>{integration.name}</div>
            <div style={{ fontSize: 12, color: 'var(--fg-3)', marginTop: 2 }}>Configure display & placement</div>
          </div>
          <window.IconButton icon="x" onClick={onClose} />
        </div>

        <div style={{ flex: 1, padding: 24, display: 'flex', flexDirection: 'column', gap: 20, overflowY: 'auto' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '12px 14px', background: 'var(--mint-tint)', borderRadius: 8 }}>
            <i data-lucide="check-circle" style={{ width: 16, height: 16, color: 'var(--mint)', flexShrink: 0 }}></i>
            <div>
              <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--mint-deep)' }}>{integration.name} connected</div>
              <div style={{ fontSize: 11, color: 'var(--mint)', marginTop: 1 }}>Syncing reviews from your Shopify store</div>
            </div>
          </div>

          <window.Select label="Reviews per product page" value={reviewCount} onChange={e => setReviewCount(e.target.value)} options={['2', '3', '5', '10', 'All']} />

          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            <label style={{ fontSize: 12, fontWeight: 500, color: 'var(--fg-2)' }}>Placement on product page</label>
            {[
              { id: 'below_description', label: 'Below product description' },
              { id: 'above_atc', label: 'Above add-to-cart button' },
              { id: 'bottom', label: 'Bottom of page' },
            ].map(opt => (
              <div key={opt.id} onClick={() => setPlacement(opt.id)} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '9px 12px', borderRadius: 8, cursor: 'pointer', background: placement === opt.id ? 'var(--ink-08)' : 'var(--paper)', border: `1px solid ${placement === opt.id ? 'var(--hairline-bold)' : 'var(--hairline)'}` }}>
                <div style={{ width: 14, height: 14, borderRadius: '50%', border: `2px solid ${placement === opt.id ? 'var(--ink)' : 'var(--sand-300)'}`, background: placement === opt.id ? 'var(--ink)' : 'transparent', flexShrink: 0 }}></div>
                <span style={{ fontSize: 13, fontWeight: placement === opt.id ? 500 : 400 }}>{opt.label}</span>
              </div>
            ))}
          </div>

          <window.Toggle checked={showRating} onChange={setShowRating} label="Show star rating summary below product title" />

          <div style={{ background: 'var(--sand-50)', borderRadius: 8, padding: '12px 14px' }}>
            <div style={{ fontSize: 11, fontWeight: 500, color: 'var(--fg-2)', marginBottom: 6 }}>Preview</div>
            <div style={{ display: 'flex', gap: 2, alignItems: 'center' }}>
              {[1,2,3,4,5].map(s => <span key={s} style={{ color: '#E8B83A', fontSize: 14 }}>★</span>)}
              <span style={{ fontSize: 12, color: 'var(--fg-2)', marginLeft: 6 }}>4.8 · 127 reviews</span>
            </div>
          </div>
        </div>

        <div style={{ padding: '16px 24px', borderTop: '1px solid var(--hairline)', display: 'flex', gap: 8 }}>
          <window.Button variant="secondary" onClick={onClose} style={{ flex: 1, justifyContent: 'center' }}>Cancel</window.Button>
          <window.Button onClick={() => { setSaved(true); setTimeout(onClose, 800); }} style={{ flex: 1, justifyContent: 'center' }}>
            {saved ? '✓ Saved' : 'Save changes'}
          </window.Button>
        </div>
      </div>
    </div>
  );
};

const IntegrationsScreen = ({ persona, tweaks }) => {
  const [integrations, setIntegrations] = React.useState(INTEGRATIONS);
  const [configuring, setConfiguring] = React.useState(null);
  const [catFilter, setCatFilter] = React.useState('All');
  const { dark } = tweaks;

  const toggle = (id) => setIntegrations(prev => prev.map(i => i.id === id ? { ...i, enabled: !i.enabled } : i));
  const cats = ['All', ...new Set(INTEGRATIONS.map(i => i.cat))];
  const filtered = catFilter === 'All' ? integrations : integrations.filter(i => i.cat === catFilter);

  const cardBg = dark ? 'rgba(255,255,255,0.06)' : 'var(--white)';
  const cardBorder = dark ? 'rgba(255,255,255,0.1)' : 'var(--hairline)';
  const textColor = dark ? 'rgba(245,241,232,0.9)' : 'var(--fg-1)';
  const subColor = dark ? 'rgba(245,241,232,0.5)' : 'var(--fg-3)';

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 24, maxWidth: 1100 }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 16 }}>
        <div>
          <h1 style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 32, color: textColor, margin: 0, lineHeight: 1.1 }}>Integrations</h1>
          <div style={{ fontSize: 13, color: subColor, marginTop: 6 }}>Connect your Shopify apps to your mobile app. All included in your plan.</div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, background: cardBg, border: `1px solid ${cardBorder}`, borderRadius: 10, padding: '10px 16px' }}>
          <i data-lucide="puzzle" style={{ width: 15, height: 15, color: subColor }}></i>
          <span style={{ fontSize: 13, color: textColor }}><strong>{integrations.filter(i => i.enabled).length}</strong> active</span>
          <span style={{ color: subColor, fontSize: 13 }}>of {integrations.length} available</span>
        </div>
      </div>

      <div style={{ display: 'flex', gap: 8 }}>
        <window.FilterPills options={cats} active={catFilter} onSelect={setCatFilter} />
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 14 }}>
        {filtered.map(intg => (
          <div key={intg.id} style={{ background: cardBg, border: `1px solid ${intg.enabled ? (dark ? 'rgba(47,111,90,0.4)' : 'rgba(47,111,90,0.3)') : cardBorder}`, borderRadius: 12, padding: 20, display: 'flex', flexDirection: 'column', gap: 14, transition: 'border-color 200ms' }}>
            {/* Header */}
            <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 10 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <div style={{ width: 40, height: 40, borderRadius: 10, background: intg.enabled ? 'var(--mint-tint)' : (dark ? 'rgba(255,255,255,0.08)' : 'var(--sand-50)'), display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                  <i data-lucide={intg.icon} style={{ width: 18, height: 18, color: intg.enabled ? 'var(--mint)' : subColor }}></i>
                </div>
                <div>
                  <div style={{ fontSize: 14, fontWeight: 600, color: textColor }}>{intg.name}</div>
                  <div style={{ display: 'flex', gap: 6, marginTop: 3 }}>
                    <span style={{ fontSize: 10, padding: '2px 7px', borderRadius: 999, background: dark ? 'rgba(255,255,255,0.08)' : 'var(--sand-50)', color: subColor, fontWeight: 500 }}>{intg.cat}</span>
                    {intg.phase !== 'MVP' && <span style={{ fontSize: 10, padding: '2px 7px', borderRadius: 999, background: 'var(--honey-tint)', color: 'var(--honey-deep)', fontWeight: 500 }}>{intg.phase}</span>}
                  </div>
                </div>
              </div>
              <window.Toggle checked={intg.enabled} onChange={() => toggle(intg.id)} />
            </div>

            {/* Description */}
            <p style={{ fontSize: 12, color: subColor, margin: 0, lineHeight: 1.55 }}>{intg.desc}</p>

            {/* Actions */}
            {intg.enabled && (
              <div style={{ paddingTop: 10, borderTop: `1px solid ${dark ? 'rgba(255,255,255,0.08)' : 'var(--hairline)'}`, display: 'flex', gap: 8 }}>
                <window.Button variant="secondary" size="sm" icon="settings" onClick={() => setConfiguring(intg)}>Configure</window.Button>
                <window.Button variant="ghost" size="sm" icon="external-link">View in app</window.Button>
              </div>
            )}
            {!intg.enabled && intg.phase !== 'MVP' && (
              <div style={{ fontSize: 11, color: subColor }}>Coming in {intg.phase}. <span style={{ color: 'var(--ink)', cursor: 'pointer', textDecoration: 'underline' }}>Get notified →</span></div>
            )}
          </div>
        ))}
      </div>

      {configuring && <ConfigureDrawer integration={configuring} onClose={() => setConfiguring(null)} />}
    </div>
  );
};

window.IntegrationsScreen = IntegrationsScreen;
