/* Submit a Review — open entry: type any product/brand/potency, rate it, queue for review. */
(function () {
  const D = window.WeedReviewDesignSystem_dcaedb;
  const { LeafInput, LeafRating, Thumbnail, Card, Select, Input, Textarea, Button, Divider, Badge, Icon, FanLeaf } = D;
  const WR = window.WR_DATA;
  const { useState, useRef } = React;

  const CATS = ['Flower', 'Pre-Rolls', 'Vapes', 'Edibles', 'Beverages', 'Concentrates', 'Tinctures', 'Topicals'];
  const CAT_ICON = { Flower: 'cannabis-leaf', 'Pre-Rolls': 'cigarette', Vapes: 'pen-line', Edibles: 'cookie', Beverages: 'cup-soda', Concentrates: 'droplet', Tinctures: 'pipette', Topicals: 'hand' };
  const SMOKEABLE = ['Flower', 'Pre-Rolls', 'Vapes', 'Concentrates'];

  const mapCat = (c) => {
    const s = (c || '').toLowerCase();
    if (s.includes('flower')) return 'Flower';
    if (s.includes('pre-roll')) return 'Pre-Rolls';
    if (s.includes('vape')) return 'Vapes';
    if (s.includes('seltzer') || s.includes('beverage') || s.includes('drink')) return 'Beverages';
    if (s.includes('edible') || s.includes('gummy')) return 'Edibles';
    if (s.includes('concentrate') || s.includes('resin') || s.includes('rosin')) return 'Concentrates';
    if (s.includes('tincture')) return 'Tinctures';
    if (s.includes('topical')) return 'Topicals';
    return 'Flower';
  };
  const detectType = (t) => {
    const s = (t || '').toLowerCase();
    if (s.includes('hybrid')) return 'Hybrid';
    if (s.includes('indica')) return 'Indica';
    if (s.includes('sativa')) return 'Sativa';
    return '';
  };
  const normBrand = (s) => String(s).toLowerCase().replace(/[^a-z0-9]/g, '');
  function canonicalBrand(input) {
    const n = normBrand(input);
    if (!n) return null;
    const list = Object.values(WR.brands);
    for (const b of list) { if (normBrand(b.name) === n) return { brand: b, exact: true }; }
    for (const b of list) { const bn = normBrand(b.name); if (bn.includes(n) || n.includes(bn)) return { brand: b, exact: false }; }
    const tokens = input.toLowerCase().split(/\s+/).filter((t) => t.length > 2);
    for (const b of list) {
      const bt = b.name.toLowerCase().split(/\s+/);
      const overlap = tokens.filter((t) => bt.some((x) => x.startsWith(t) || t.startsWith(x))).length;
      if (overlap >= 2 || (overlap >= 1 && tokens.length === 1)) return { brand: b, exact: false };
    }
    return null;
  }

  const Wrap = ({ children, style }) => (
    <div style={{ maxWidth: 'var(--container-narrow)', margin: '0 auto', padding: '0 var(--space-7)', ...style }}>{children}</div>
  );
  const StepLabel = ({ n, children }) => (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 16 }}>
      <span style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 26, height: 26, borderRadius: '50%', background: 'var(--surface-leaf-soft)', color: 'var(--sage-700)', fontFamily: 'var(--font-sans)', fontWeight: 700, fontSize: 13 }}>{n}</span>
      <h2 style={{ fontFamily: 'var(--font-serif)', fontSize: 'var(--text-lg)', fontWeight: 600, color: 'var(--text-heading)' }}>{children}</h2>
    </div>
  );
  const FieldLabel = ({ children }) => (
    <label className="u-label" style={{ color: 'var(--text-muted)', display: 'block', marginBottom: 6 }}>{children}</label>
  );

  const INFO = {
    Appearance: 'Bud structure, trichome frost, trim quality, and color.',
    Aroma: 'The nose — how it smells in the jar and once broken up.',
    Flavor: 'Taste on the inhale and the exhale.',
    High: 'Character and quality of the effect — head vs. body, onset, and how long it lasts.',
    Smoothness: 'How smooth or harsh it feels on the throat and lungs.',
    Value: 'Overall quality for the price you paid.',
    Onset: 'How quickly the effect comes on after your dose.',
  };

  function RatingRow({ label, info, value, onChange }) {
    const [open, setOpen] = useState(false);
    return (
      <div style={{ position: 'relative', display: 'flex', alignItems: 'center', justifyContent: 'flex-start', gap: 20 }} onMouseLeave={() => setOpen(false)}>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, minWidth: 150, fontFamily: 'var(--font-sans)', fontWeight: 600, fontSize: 15, color: 'var(--text-body)' }}>
          {label}
          {info && (
            <button type="button" aria-label={label + ' — what is this?'} onClick={() => setOpen((o) => !o)} onMouseEnter={() => setOpen(true)}
              style={{ display: 'inline-flex', padding: 0, border: 'none', background: 'none', color: open ? 'var(--sage-600)' : 'var(--text-faint)', cursor: 'pointer', lineHeight: 0 }}>
              <Icon name="info" size={15} />
            </button>
          )}
          {open && info && (
            <span role="tooltip" style={{ position: 'absolute', top: 'calc(100% + 6px)', left: 0, zIndex: 40, width: 232, padding: '10px 13px', background: 'var(--forest-800)', color: 'var(--text-on-forest)', fontWeight: 400, fontSize: 13, lineHeight: 1.45, borderRadius: 'var(--radius-md)', boxShadow: 'var(--shadow-lg)' }}>{info}</span>
          )}
        </span>
        <LeafInput value={value} onChange={onChange} size={48} />
      </div>
    );
  }

  function Seg({ options, value, onChange }) {
    return (
      <div style={{ display: 'inline-flex', gap: 2, padding: 4, background: 'var(--cream-300)', borderRadius: 'var(--radius-pill)' }}>
        {options.map((opt) => {
          const on = value === opt;
          return <button key={opt} type="button" onClick={() => onChange(opt)} style={{ height: 34, padding: '0 15px', border: 'none', borderRadius: 'var(--radius-pill)', background: on ? 'var(--surface-raised)' : 'transparent', color: on ? 'var(--forest-700)' : 'var(--text-muted)', boxShadow: on ? 'var(--shadow-sm)' : 'none', fontFamily: 'var(--font-sans)', fontWeight: 600, fontSize: 14, cursor: 'pointer', transition: 'var(--transition-colors)', whiteSpace: 'nowrap' }}>{opt}</button>;
        })}
      </div>
    );
  }

  function SubmitReviewPage({ navigate, id }) {
    const [narrow, setNarrow] = useState(false);
    React.useEffect(() => {
      const mq = window.matchMedia('(max-width: 560px)');
      const on = () => setNarrow(mq.matches); on();
      mq.addEventListener ? mq.addEventListener('change', on) : mq.addListener(on);
      return () => { mq.removeEventListener ? mq.removeEventListener('change', on) : mq.removeListener(on); };
    }, []);
    const init = id && WR.products[id] ? WR.products[id] : null;
    const [productName, setProductName] = useState(init ? init.name : '');
    const [brandInput, setBrandInput] = useState(init ? WR.brandName(init.brand) : '');
    const [category, setCategory] = useState(init ? mapCat(init.category) : 'Flower');
    const [thc, setThc] = useState(init ? init.thc : '');
    const [strainType, setStrainType] = useState(init ? detectType(init.type) : '');
    const [buyAgain, setBuyAgain] = useState(null);
    const [highMatch, setHighMatch] = useState(null);
    const [pTone, setPTone] = useState(init ? init.tone : 'sage');
    const [openList, setOpenList] = useState(false);
    const [scores, setScores] = useState({});
    const [couchLock, setCouchLock] = useState(null);
    const [device, setDevice] = useState('Joint');
    const [text, setText] = useState('');
    const [photos, setPhotos] = useState([]);
    const [receipt, setReceipt] = useState(null);
    const [done, setDone] = useState(false);
    const fileRef = useRef(null);
    const receiptRef = useRef(null);

    const smokeable = SMOKEABLE.includes(category);
    const baseRubric = smokeable ? ['Appearance', 'Aroma', 'Flavor', 'Effect'] : ['Flavor', 'Onset', 'Effect', 'Value'];
    const rubric = baseRubric.map((l) => (l === 'Effect' ? 'High' : l)).concat(smokeable ? ['Smoothness', 'Value'] : []);
    const matched = canonicalBrand(brandInput);

    const vals = rubric.map((k) => scores[k]).filter((v) => v != null);
    const overall = vals.length ? vals.reduce((a, b) => a + b, 0) / vals.length : 0;
    const complete = productName.trim() && brandInput.trim() && vals.length === rubric.length && text.trim().length > 0;

    const suggestions = WR.order.products.filter((x) => {
      const q = productName.trim().toLowerCase();
      const pp = WR.products[x];
      return q && pp.name.toLowerCase() !== q && (pp.name.toLowerCase().includes(q) || pp.category.toLowerCase().includes(q) || WR.brandName(pp.brand).toLowerCase().includes(q));
    });
    const pickProduct = (x) => {
      const pp = WR.products[x];
      setProductName(pp.name); setBrandInput(WR.brandName(pp.brand)); setCategory(mapCat(pp.category)); setThc(pp.thc); setPTone(pp.tone); setStrainType(detectType(pp.type)); setOpenList(false);
    };

    const resetForm = () => { setProductName(''); setBrandInput(''); setThc(''); setStrainType(''); setBuyAgain(null); setHighMatch(null); setScores({}); setCouchLock(null); setDevice('Joint'); setText(''); setPhotos([]); setReceipt(null); };

    if (done) {
      const brandLine = matched
        ? (matched.exact
          ? <React.Fragment>Filed under <b style={{ color: 'var(--text-body)' }}>{matched.brand.name}</b>.</React.Fragment>
          : <React.Fragment>We matched “{brandInput.trim()}” to the verified brand <b style={{ color: 'var(--text-body)' }}>{matched.brand.name}</b>.</React.Fragment>)
        : <React.Fragment>New brand <b style={{ color: 'var(--text-body)' }}>“{brandInput.trim()}”</b> — a WeedReview brand page will be generated once your review clears review.</React.Fragment>;
      return (
        <Wrap style={{ padding: '72px var(--space-7)' }}>
          <Card padding="lg" elevation="sm" style={{ textAlign: 'center' }}>
            <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 14 }}><FanLeaf size={52} /></div>
            <h1 style={{ fontFamily: 'var(--font-display)', fontSize: 'var(--text-3xl)', fontWeight: 600, color: 'var(--text-heading)' }}>Added to the review queue</h1>
            <p style={{ color: 'var(--text-muted)', margin: '10px auto 4px', maxWidth: 460, lineHeight: 1.6 }}>
              Your {overall.toFixed(1)}-leaf review of <b style={{ color: 'var(--text-body)' }}>{productName.trim()}</b> is in. Our editors verify every submission before it goes live — usually within 24 hours.
            </p>
            <p style={{ color: 'var(--text-muted)', margin: '0 auto 16px', maxWidth: 460, lineHeight: 1.6 }}>{brandLine}</p>
            {receipt && <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 14 }}><Badge variant="verified">Verified purchase</Badge></div>}
            <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 24 }}><LeafRating value={overall} size="lg" /></div>
            <div style={{ display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap' }}>
              {matched && <Button onClick={() => navigate('brand', matched.brand.id)}>View {matched.brand.name}</Button>}
              <Button variant="secondary" onClick={() => { setDone(false); resetForm(); }}>Write another</Button>
            </div>
          </Card>
        </Wrap>
      );
    }

    return (
      <div style={{ paddingBottom: 80, background: 'linear-gradient(180deg, #E6EEDE 0%, #F2EFE6 480px)', minHeight: 'calc(100vh - var(--nav-height))' }}>
        <Wrap style={{ padding: '40px var(--space-7) 8px' }}>
          <div className="u-label" style={{ color: 'var(--sage-600)', marginBottom: 8 }}>Contribute</div>
          <h1 style={{ fontFamily: 'var(--font-display)', fontSize: 'var(--text-4xl)', fontWeight: 600, color: 'var(--text-heading)', letterSpacing: '-0.02em' }}>Write a Review</h1>
          <p style={{ color: 'var(--text-muted)', fontSize: 'var(--text-md)', marginTop: 8, maxWidth: 580 }}>Review anything — even a product or brand we don't list yet. New brands get a page once your review is approved.</p>
        </Wrap>

        <Wrap style={{ paddingTop: 24 }}>
          <Card padding="lg" elevation="sm">
            {/* Step 1 — what */}
            <StepLabel n={1}>What are you reviewing?</StepLabel>
            <div style={{ display: 'flex', gap: 18, alignItems: 'flex-start' }}>
              <div style={{ width: 76, flex: 'none' }}><Thumbnail tone={pTone} icon={CAT_ICON[category]} ratio="1 / 1" radius="var(--radius-md)" /></div>
              <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', gap: 16 }}>
                <div style={{ position: 'relative' }}>
                  <Input label="Product name" icon="search" placeholder="e.g. Blue Dream, or type a new product…" value={productName}
                    onChange={(e) => { setProductName(e.target.value); setOpenList(true); }}
                    onFocus={() => setOpenList(true)}
                    onBlur={() => setTimeout(() => setOpenList(false), 130)} />
                  {openList && suggestions.length > 0 && (
                    <div style={{ position: 'absolute', top: '100%', left: 0, right: 0, zIndex: 30, marginTop: 6, background: 'var(--surface-raised)', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-md)', boxShadow: 'var(--shadow-lg)', maxHeight: 240, overflowY: 'auto' }}>
                      {suggestions.map((x, i) => (
                        <button key={x} type="button" onMouseDown={(e) => { e.preventDefault(); pickProduct(x); }}
                          style={{ display: 'flex', gap: 10, alignItems: 'center', width: '100%', padding: '10px 12px', background: 'transparent', border: 'none', borderBottom: i < suggestions.length - 1 ? '1px solid var(--divider)' : 'none', cursor: 'pointer', textAlign: 'left' }}>
                          <Icon name={WR.products[x].icon} size={16} color="var(--sage-600)" />
                          <span style={{ fontFamily: 'var(--font-sans)', fontWeight: 600, fontSize: 15, color: 'var(--text-body)' }}>{WR.products[x].name}</span>
                          <span style={{ fontSize: 13, color: 'var(--text-muted)' }}>{WR.products[x].category} · {WR.brandName(WR.products[x].brand)}</span>
                        </button>
                      ))}
                    </div>
                  )}
                </div>

                <div>
                  <Input label="Brand" icon="building-2" placeholder="e.g. Emerald Coast Farms" value={brandInput} onChange={(e) => setBrandInput(e.target.value)} />
                  {brandInput.trim() && (
                    <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 7, fontSize: 13, fontWeight: 600,
                      color: matched ? (matched.exact ? 'var(--sage-700)' : 'var(--amber-700)') : 'var(--sage-600)' }}>
                      {matched
                        ? <React.Fragment><Icon name={matched.exact ? 'badge-check' : 'corner-down-right'} size={14} />
                            {matched.exact ? <span>Verified brand — {matched.brand.name}</span> : <span>We'll list this under <b>{matched.brand.name}</b></span>}
                          </React.Fragment>
                        : <React.Fragment><Icon name="sparkles" size={14} /><span>New brand — a WeedReview page will be generated after review</span></React.Fragment>}
                    </div>
                  )}
                </div>

                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 16 }}>
                  <div>
                    <FieldLabel>Category</FieldLabel>
                    <Select options={CATS} value={category} onChange={(e) => { setCategory(e.target.value); setScores({}); }} />
                  </div>
                  <Input label="THC / Potency" icon="flask-conical" placeholder="e.g. 22% THC or 5mg" value={thc} onChange={(e) => setThc(e.target.value)} />
                </div>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 16 }}>
                  <div>
                    <FieldLabel>Strain type</FieldLabel>
                    <Seg options={['Sativa', 'Indica', 'Hybrid']} value={strainType} onChange={setStrainType} />
                  </div>
                  <div>
                    <FieldLabel>Would you buy again?</FieldLabel>
                    <Seg options={['Yes', 'No']} value={buyAgain} onChange={setBuyAgain} />
                  </div>
                </div>
              </div>
            </div>

            <Divider style={{ margin: 'var(--space-8) 0' }} />

            {/* Step 2 — ratings */}
            <StepLabel n={2}>Rate the experience</StepLabel>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr', gap: '14px' }}>
              {rubric.map((label) => (
                <RatingRow key={label} label={label} info={INFO[label]} value={scores[label] || 0}
                  onChange={(v) => setScores((s) => ({ ...s, [label]: v }))} />
              ))}
            </div>
            {smokeable && (
              <div style={{ display: 'grid', gridTemplateColumns: '1fr', gap: '14px', marginTop: 20, paddingTop: 20, borderTop: '1px solid var(--divider)' }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 16 }}>
                  <span style={{ fontFamily: 'var(--font-sans)', fontWeight: 600, fontSize: 15, color: 'var(--text-body)' }}>Couch lock?</span>
                  <div style={{ display: 'inline-flex', gap: 2, padding: 4, background: 'var(--cream-300)', borderRadius: 'var(--radius-pill)' }}>
                    {['No', 'Yes'].map((opt) => {
                      const on = couchLock === opt;
                      return <button key={opt} type="button" onClick={() => setCouchLock(opt)} style={{ height: 32, padding: '0 20px', border: 'none', borderRadius: 'var(--radius-pill)', background: on ? 'var(--surface-raised)' : 'transparent', color: on ? 'var(--forest-700)' : 'var(--text-muted)', boxShadow: on ? 'var(--shadow-sm)' : 'none', fontFamily: 'var(--font-sans)', fontWeight: 600, fontSize: 14, cursor: 'pointer', transition: 'var(--transition-colors)' }}>{opt}</button>;
                    })}
                  </div>
                </div>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 16 }}>
                  <span style={{ fontFamily: 'var(--font-sans)', fontWeight: 600, fontSize: 15, color: 'var(--text-body)' }}>Smoking device</span>
                  <div style={{ minWidth: 168 }}><Select options={['Joint', 'Blunt', 'Pipe', 'Bong', 'Vaporizer', 'Dab rig']} value={device} onChange={(e) => setDevice(e.target.value)} /></div>
                </div>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 16 }}>
                  <span style={{ fontFamily: 'var(--font-sans)', fontWeight: 600, fontSize: 15, color: 'var(--text-body)' }}>High vs. advertised</span>
                  <Seg options={['Weaker', 'As advertised', 'Stronger']} value={highMatch} onChange={setHighMatch} />
                </div>
              </div>
            )}
            <div style={{ display: 'flex', alignItems: 'center', flexWrap: 'wrap', gap: 14, marginTop: 22, padding: '14px 18px', background: 'var(--surface-leaf-soft)', borderRadius: 'var(--radius-md)' }}>
              <span className="u-label" style={{ color: 'var(--sage-700)' }}>Overall</span>
              <LeafRating value={overall} size={narrow ? 26 : 48} />
              <span style={{ fontSize: 13, color: 'var(--sage-700)', marginLeft: 'auto' }}>{vals.length}/{rubric.length} rated · auto-averaged</span>
            </div>

            <Divider style={{ margin: 'var(--space-8) 0' }} />

            {/* Step 3 — text */}
            <StepLabel n={3}>Describe it</StepLabel>
            <Textarea rows={5} placeholder="Appearance, aroma, flavor, the high — what stood out?" value={text} onChange={(e) => setText(e.target.value)} />

            <Divider style={{ margin: 'var(--space-8) 0' }} />

            {/* Step 4 — photos */}
            <StepLabel n={4}>Add photos <span style={{ fontWeight: 400, color: 'var(--text-faint)', fontSize: 13 }}>(optional)</span></StepLabel>
            <input ref={fileRef} type="file" accept="image/*" multiple style={{ display: 'none' }} onChange={(e) => setPhotos(Array.from(e.target.files || []).map((f) => f.name))} />
            <button type="button" onClick={() => fileRef.current && fileRef.current.click()}
              style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8, width: '100%', padding: '28px', border: '1.5px dashed var(--border-strong)', borderRadius: 'var(--radius-lg)', background: 'var(--surface-page-alt)', cursor: 'pointer', color: 'var(--text-muted)' }}>
              <Icon name="image-plus" size={26} color="var(--sage-500)" />
              <span style={{ fontFamily: 'var(--font-sans)', fontWeight: 600, fontSize: 14 }}>Drag photos here or click to upload</span>
              {photos.length > 0 && <span style={{ fontSize: 13, color: 'var(--sage-700)' }}>{photos.length} photo{photos.length > 1 ? 's' : ''} added</span>}
            </button>

            <Divider style={{ margin: 'var(--space-8) 0' }} />

            {/* Step 5 — verify */}
            <StepLabel n={5}>Verify your purchase <span style={{ fontWeight: 400, color: 'var(--text-faint)', fontSize: 13 }}>(optional)</span></StepLabel>
            <input ref={receiptRef} type="file" accept="image/*,application/pdf" style={{ display: 'none' }} onChange={(e) => setReceipt((e.target.files && e.target.files[0]) ? e.target.files[0].name : null)} />
            <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '16px 18px', border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-lg)', background: receipt ? 'var(--surface-leaf-soft)' : 'var(--surface-page-alt)' }}>
              <Icon name={receipt ? 'badge-check' : 'receipt'} size={26} color={receipt ? 'var(--sage-600)' : 'var(--text-faint)'} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontFamily: 'var(--font-sans)', fontWeight: 600, fontSize: 15, color: 'var(--text-body)' }}>{receipt ? 'Proof attached — your review will be Verified' : 'Attach a receipt or a photo of the container'}</div>
                <div style={{ fontSize: 13, color: 'var(--text-muted)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{receipt ? receipt : 'A receipt, or a photo above showing the product jar/container, earns a Verified badge.'}</div>
              </div>
              {receipt
                ? <Button variant="ghost" size="sm" onClick={() => { setReceipt(null); if (receiptRef.current) receiptRef.current.value = ''; }}>Remove</Button>
                : <Button variant="secondary" size="sm" iconLeft="upload" onClick={() => receiptRef.current && receiptRef.current.click()}>Attach proof</Button>}
            </div>

            <div style={{ marginTop: 10, fontSize: 12, color: 'var(--text-faint)', fontStyle: 'italic', lineHeight: 1.4 }}>Disclaimer: if the product jar or container is clearly visible in a photo you add above — and shown publicly on your review — it will also count as Verified.</div>

            <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginTop: 'var(--space-8)', flexWrap: 'wrap' }}>
              <Button size="lg" disabled={!complete} onClick={() => setDone(true)}>Submit for Review</Button>
              <span style={{ fontSize: 13, color: 'var(--text-faint)' }}>{complete ? 'Goes to the moderation queue' : 'Add a product, brand, ratings, and a description to submit.'}</span>
            </div>
          </Card>
        </Wrap>
      </div>
    );
  }
  window.SubmitReviewPage = SubmitReviewPage;
})();
