// Seller dashboard + add/edit product flow.

const { useState: useS_d } = React;

function Dashboard({ profile, products, onBack, onAddProduct, onEditProduct, onOpenPublic, onOpenShop, onEditProfile, onEditSocials, onEditLinks, onTogglePublished }) {
  const total = products.length;
  const published = products.filter(p => p.published).length;
  const outStock = products.filter(p => p.stock === 0).length;

  return (
    <div style={{ height:'100%', display:'flex', flexDirection:'column' }}>
      <div style={{ padding:'54px 16px 8px' }}>
        <div style={{ display:'flex', alignItems:'center', gap:10 }}>
          <IconButton icon={<IconBack size={20}/>} onClick={onBack} bg="rgba(0,0,0,0.05)"/>
          <div style={{ flex:1, fontSize:17, fontWeight:600 }}>Dashboard</div>
          <IconButton icon={<IconEye size={17}/>} onClick={onOpenPublic} bg="rgba(0,0,0,0.05)"/>
        </div>
      </div>

      <div style={{ flex:1, overflow:'auto', padding:'10px 16px 100px' }}>
        {/* profile card */}
        <div style={{
          background:'#fff', borderRadius:20, padding:16,
          display:'flex', gap:12, alignItems:'center', boxShadow: HUUL_TOKENS.shadow.card,
          marginBottom:14,
        }}>
          <Avatar profile={profile} size={52}/>
          <div style={{ flex:1, minWidth:0 }}>
            <div style={{ fontSize:16, fontWeight:600, letterSpacing:-0.2 }}>{profile.businessName}</div>
            <div style={{ fontSize:13, color:HUUL_TOKENS.color.ink3, marginTop:2,
              display:'flex', alignItems:'center', gap:4 }}>
              huul.so/{profile.username}
              <IconCopy size={12}/>
            </div>
          </div>
          <IconButton icon={<IconEdit size={16}/>} onClick={onEditProfile} bg="rgba(0,0,0,0.05)"/>
        </div>

        {/* stats row */}
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:8, marginBottom:16 }}>
          <StatCard label="Products" value={total}/>
          <StatCard label="Live" value={published}/>
          <StatCard label="Out" value={outStock} warn={outStock > 0}/>
        </div>

        {/* products header */}
        <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', padding:'6px 4px 10px' }}>
          <div style={{ fontSize:17, fontWeight:600 }}>Products</div>
          <button onClick={onAddProduct} style={{
            border:'none', background:HUUL_TOKENS.color.accent, color:'#fff',
            fontSize:13, fontWeight:600, padding:'7px 12px 7px 10px',
            borderRadius:99, cursor:'pointer', fontFamily:HUUL_TOKENS.font.stack,
            display:'inline-flex', alignItems:'center', gap:3,
            boxShadow: '0 2px 8px rgba(10,132,255,0.3)',
          }}><IconPlus size={14}/> Add</button>
        </div>

        <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
          {products.map(p => (
            <DashProductRow key={p.id} product={p} onEdit={() => onEditProduct(p)} onToggle={() => onTogglePublished(p.id)}/>
          ))}

          {products.length === 0 && (
            <div style={{
              background:'#fff', borderRadius:20, padding:'32px 20px',
              textAlign:'center', boxShadow: HUUL_TOKENS.shadow.card,
            }}>
              <div style={{ fontSize:36, marginBottom:8 }}>📦</div>
              <div style={{ fontSize:16, fontWeight:600, marginBottom:4 }}>No products yet</div>
              <div style={{ fontSize:13.5, color:HUUL_TOKENS.color.ink3, lineHeight:1.45, marginBottom:16 }}>
                Add your first product to start showing it on your shop.
              </div>
              <button onClick={onAddProduct} style={{
                border:'none', background:HUUL_TOKENS.color.accent, color:'#fff',
                fontSize:15, fontWeight:600, padding:'12px 24px',
                borderRadius:99, cursor:'pointer', fontFamily:HUUL_TOKENS.font.stack,
                display:'inline-flex', alignItems:'center', gap:6,
                boxShadow: HUUL_TOKENS.shadow.btn,
              }}><IconPlus size={16}/> Add your first product</button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function QuickAction({ icon, label, onClick }) {
  return (
    <button onClick={onClick} style={{
      border:'none', background:'#fff', borderRadius:16, padding:'14px 12px',
      boxShadow: HUUL_TOKENS.shadow.card, cursor:'pointer',
      fontFamily: HUUL_TOKENS.font.stack,
      display:'flex', alignItems:'center', gap:10, width:'100%',
    }}>
      <div style={{
        width:34, height:34, borderRadius:10, background:'rgba(10,132,255,0.08)',
        display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0,
        color: HUUL_TOKENS.color.accent,
      }}>{icon}</div>
      <div style={{ textAlign:'left' }}>
        <div style={{ fontSize:14, fontWeight:600, color: HUUL_TOKENS.color.ink }}>{label}</div>
        <div style={{ fontSize:11.5, color: HUUL_TOKENS.color.ink3, marginTop:1 }}>Edit</div>
      </div>
    </button>
  );
}

function StatCard({ label, value, warn }) {
  return (
    <div style={{
      background:'#fff', borderRadius:16, padding:'14px 12px',
      boxShadow: HUUL_TOKENS.shadow.card,
    }}>
      <div style={{ fontSize:22, fontWeight:700, letterSpacing:-0.4,
        color: warn ? HUUL_TOKENS.color.warn : HUUL_TOKENS.color.ink }}>{value}</div>
      <div style={{ fontSize:12, color:HUUL_TOKENS.color.ink3, marginTop:2 }}>{label}</div>
    </div>
  );
}

function DashProductRow({ product, onEdit, onToggle }) {
  return (
    <div
      onClick={onEdit}
      style={{
        background:'#fff', borderRadius:16, padding:10, display:'flex', gap:12,
        alignItems:'center', boxShadow: HUUL_TOKENS.shadow.card, cursor:'pointer',
      }}>
      <img src={product.image} alt="" style={{
        width:56, height:56, borderRadius:12, objectFit:'cover', flexShrink:0,
        opacity: product.stock === 0 ? 0.55 : 1,
      }}/>
      <div style={{ flex:1, minWidth:0 }}>
        <div style={{ fontSize:15, fontWeight:600, letterSpacing:-0.2,
          whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{product.name}</div>
        <div style={{ fontSize:12.5, color:HUUL_TOKENS.color.ink3, marginTop:2,
          display:'flex', alignItems:'center', gap:6 }}>
          <span>{product.priceLabel}</span>
          <span>·</span>
          <span>{product.stock === 0 ? 'Out of stock' : `${product.stock} in stock`}</span>
        </div>
      </div>
      <div onClick={(e)=>{e.stopPropagation(); onToggle();}}>
        <Switch on={product.published}/>
      </div>
    </div>
  );
}

function Switch({ on }) {
  return (
    <div style={{
      width:44, height:26, borderRadius:13,
      background: on ? HUUL_TOKENS.color.success : 'rgba(0,0,0,0.14)',
      position:'relative', transition:'background 180ms',
      cursor:'pointer', flexShrink:0,
    }}>
      <div style={{
        position:'absolute', top:2, left: on ? 20 : 2,
        width:22, height:22, borderRadius:11, background:'#fff',
        boxShadow:'0 1px 3px rgba(0,0,0,0.2)',
        transition:'left 180ms cubic-bezier(.4,0,.2,1)',
      }}/>
    </div>
  );
}

// ─── Product editor (add / edit) ─────────────────────────────
function ProductEditor({ initial, onSave, onDelete, onClose }) {
  const isNew = !initial?.id;
  const [name, setName] = useS_d(initial?.name || '');
  const [desc, setDesc] = useS_d(initial?.desc || '');
  const [price, setPrice] = useS_d(initial?.priceLabel?.replace(/[^0-9.]/g, '') || '');
  const [category, setCategory] = useS_d(initial?.category || 'Fashion');
  const [stock, setStock] = useS_d(initial?.stock ?? 10);
  const [image, setImage] = useS_d(initial?.image || null);
  const [paletteIdx, setPaletteIdx] = useS_d(0);

  const palettes = [
    ['#E8D4B8', '#C49A6C', '#6B4A2B'],
    ['#A8C8E8', '#5A8AB8', '#1E3A5A'],
    ['#F2E4C4', '#C49A4C', '#5A3F18'],
    ['#DCDCE0', '#8A8A90', '#2A2A2E'],
    ['#D4B58A', '#8B5E3C', '#3A2818'],
    ['#F0E8DA', '#B8A888', '#4A3F2E'],
  ];

  const pickPaletteImage = (i) => {
    setPaletteIdx(i);
    setImage(window.HUUL_DATA.placeholderSVG(palettes[i], name || 'product'));
  };

  const canSave = name.trim().length >= 2 && price && image;

  const save = () => {
    onSave({
      id: initial?.id || 'p_' + Math.random().toString(36).slice(2,8),
      name: name.trim(),
      desc: desc.trim() || 'No description.',
      priceLabel: '$' + price.replace(/[^\d.]/g, ''),
      price: parseFloat(price) || 0,
      currency: 'USD',
      category,
      stock: parseInt(stock) || 0,
      image,
      published: initial?.published ?? true,
    });
  };

  return (
    <div style={{ height:'100%', display:'flex', flexDirection:'column' }}>
      <div style={{
        padding:'54px 16px 8px', display:'flex', alignItems:'center', justifyContent:'space-between',
      }}>
        <GhostButton onClick={onClose}>Cancel</GhostButton>
        <div style={{ fontSize:16, fontWeight:600 }}>{isNew ? 'New product' : 'Edit product'}</div>
        <button onClick={canSave ? save : undefined} disabled={!canSave}
          style={{
            border:'none', background:'transparent',
            color: canSave ? HUUL_TOKENS.color.accent : HUUL_TOKENS.color.ink4,
            fontSize:16, fontWeight:600, cursor: canSave ? 'pointer' : 'not-allowed',
            fontFamily: HUUL_TOKENS.font.stack,
          }}>Save</button>
      </div>

      <div style={{ flex:1, overflow:'auto', padding:'10px 16px 100px' }}>
        {/* image picker */}
        <div style={{
          background:'#fff', borderRadius:20, padding:16,
          boxShadow: HUUL_TOKENS.shadow.card, marginBottom:14,
        }}>
          <HuulLabel>Product image</HuulLabel>
          {image ? (
            <div style={{ position:'relative' }}>
              <img src={image} alt="" style={{
                width:'100%', aspectRatio:'1', objectFit:'cover', borderRadius:14,
              }}/>
              <IconButton icon={<IconX size={16}/>} onClick={() => setImage(null)}
                style={{ position:'absolute', top:8, right:8 }}
                bg="rgba(255,255,255,0.95)"/>
            </div>
          ) : (
            <div>
              <div style={{ fontSize:12, color:HUUL_TOKENS.color.ink3, marginBottom:8, padding:'0 4px' }}>
                Pick a placeholder palette (upload will be available on the real app):
              </div>
              <div style={{ display:'grid', gridTemplateColumns:'repeat(6, 1fr)', gap:8 }}>
                {palettes.map((p, i) => (
                  <button key={i} onClick={() => pickPaletteImage(i)} style={{
                    aspectRatio:'1', border:'none', borderRadius:12,
                    background: `linear-gradient(135deg, ${p[0]} 0%, ${p[1]} 100%)`,
                    cursor:'pointer', padding:0, boxShadow:'0 1px 3px rgba(0,0,0,0.08)',
                  }}/>
                ))}
              </div>
              <div style={{
                marginTop:10, padding:'12px', background:'rgba(0,0,0,0.03)',
                borderRadius:12, display:'flex', alignItems:'center', gap:10,
                fontSize:13.5, color: HUUL_TOKENS.color.ink2,
              }}>
                <IconCamera size={18} color={HUUL_TOKENS.color.ink3}/>
                Upload from camera / gallery
              </div>
            </div>
          )}
        </div>

        {/* fields */}
        <div style={{
          background:'#fff', borderRadius:20, padding:16,
          boxShadow: HUUL_TOKENS.shadow.card, marginBottom:14,
          display:'flex', flexDirection:'column', gap:14,
        }}>
          <div>
            <HuulLabel>Name</HuulLabel>
            <TextField value={name} onChange={setName} placeholder="e.g. Linen Abaya"
              style={{ boxShadow:'none', background:'rgba(0,0,0,0.04)' }}/>
          </div>
          <div>
            <HuulLabel>Description</HuulLabel>
            <TextField value={desc} onChange={setDesc} multiline rows={3}
              placeholder="A short description buyers will see"
              style={{ boxShadow:'none', background:'rgba(0,0,0,0.04)' }}/>
          </div>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:10 }}>
            <div>
              <HuulLabel>Price (USD)</HuulLabel>
              <TextField value={price} onChange={(v)=>setPrice(v.replace(/[^\d.]/g,''))} prefix="$"
                style={{ boxShadow:'none', background:'rgba(0,0,0,0.04)' }}/>
            </div>
            <div>
              <HuulLabel>Stock</HuulLabel>
              <TextField value={String(stock)} onChange={(v)=>setStock(v.replace(/\D/g,''))}
                style={{ boxShadow:'none', background:'rgba(0,0,0,0.04)' }}/>
            </div>
          </div>
          <div>
            <HuulLabel>Category</HuulLabel>
            <div style={{ display:'flex', gap:8, flexWrap:'wrap' }}>
              {['Fashion', 'Home', 'Electronics', 'Food', 'Beauty', 'Other'].map(c => (
                <button key={c} onClick={() => setCategory(c)} style={{
                  border:'none', background: category===c ? HUUL_TOKENS.color.ink : 'rgba(0,0,0,0.05)',
                  color: category===c ? '#fff' : HUUL_TOKENS.color.ink2,
                  fontSize:13, padding:'8px 14px', borderRadius:99, cursor:'pointer',
                  fontFamily: HUUL_TOKENS.font.stack, fontWeight:500,
                }}>{c}</button>
              ))}
            </div>
          </div>
        </div>

        {!isNew && (
          <button onClick={() => onDelete(initial.id)} style={{
            width:'100%', height:50, borderRadius:14, border:'none',
            background:'rgba(255,59,48,0.08)', color: HUUL_TOKENS.color.danger,
            fontSize:15, fontWeight:500, cursor:'pointer', fontFamily: HUUL_TOKENS.font.stack,
            display:'flex', alignItems:'center', justifyContent:'center', gap:8,
          }}>
            <IconTrash size={16}/> Delete product
          </button>
        )}
      </div>
    </div>
  );
}

window.Dashboard = Dashboard;
window.ProductEditor = ProductEditor;
