// Green Voice — Review writing flow

function GVReviewFlow({ nav, initialCourseId }) {
  const course = GV_COURSES.find(c => c.id === initialCourseId) || GV_COURSES[0];
  const [step, setStep] = React.useState(0);
  const [ratings, setRatings] = React.useState({
    green: 8, caddie: 8, halfway: 8, facility: 8, pace: 8, price: 8,
  });
  const [tags, setTags] = React.useState([]);
  const [reviewText, setReviewText] = React.useState('');
  const [photos, setPhotos] = React.useState([]);

  const stepCount = 4;

  return (
    <div style={{ background: GV.color.surface, minHeight: '100%', display: 'flex', flexDirection: 'column' }}>
      {/* Header */}
      <div style={{
        display: 'flex',
        alignItems: 'center',
        padding: '12px 16px',
        borderBottom: `1px solid ${GV.color.borderSubtle}`,
        gap: 12,
        flexShrink: 0,
      }}>
        <button
          onClick={step === 0 ? nav.back : () => setStep(step - 1)}
          style={{ background: 'none', border: 'none', padding: 4, cursor: 'pointer', color: GV.color.forestDeep, display: 'flex' }}
        >
          <Icon name="arrow_back" size={22} />
        </button>
        <div style={{ flex: 1 }}>
          <div style={{
            fontFamily: GV.font.serif,
            fontSize: 15,
            fontWeight: 600,
            color: GV.color.forestDeep,
          }}>리뷰 작성 · {course.name}</div>
          <div style={{
            fontFamily: GV.font.sans,
            fontSize: 11,
            color: GV.color.outline,
          }}>STEP {step + 1} / {stepCount}</div>
        </div>
        <button onClick={nav.back} style={{ background: 'none', border: 'none', padding: 4, cursor: 'pointer', color: GV.color.outline, display: 'flex' }}>
          <Icon name="close" size={22} />
        </button>
      </div>

      {/* Progress */}
      <div style={{ height: 4, background: GV.color.surfaceContainer, flexShrink: 0 }}>
        <div style={{
          height: '100%',
          width: `${((step + 1) / stepCount) * 100}%`,
          background: GV.color.forestDeep,
          transition: 'width 0.4s ease',
        }} />
      </div>

      <div style={{ flex: 1, overflowY: 'auto' }}>
        {step === 0 && <ReviewStepRating ratings={ratings} setRatings={setRatings} course={course} onNext={() => setStep(1)} />}
        {step === 1 && <ReviewStepPhotos photos={photos} setPhotos={setPhotos} course={course} onNext={() => setStep(2)} />}
        {step === 2 && <ReviewStepText text={reviewText} setText={setReviewText} tags={tags} setTags={setTags} onNext={() => setStep(3)} />}
        {step === 3 && <ReviewStepComplete course={course} nav={nav} ratings={ratings} tagCount={tags.length} />}
      </div>
    </div>
  );
}

function ReviewStepRating({ ratings, setRatings, course, onNext }) {
  const set = (k, v) => setRatings({ ...ratings, [k]: v });
  const avg = Object.values(ratings).reduce((a, b) => a + b, 0) / Object.values(ratings).length;

  return (
    <div style={{ padding: '24px 20px 40px' }}>
      <h2 style={{
        fontFamily: GV.font.serif,
        fontSize: 22,
        fontWeight: 600,
        color: GV.color.forestDeep,
        margin: 0,
        letterSpacing: '-0.015em',
      }}>6개 품질 축을 평가해주세요</h2>
      <p style={{
        fontFamily: GV.font.sans,
        fontSize: 13,
        color: GV.color.onSurfaceVariant,
        margin: '6px 0 0',
        lineHeight: 1.5,
      }}>각 축은 1~10점으로 평가합니다. 정확한 평가가 신뢰 지수를 높입니다.</p>

      {/* Average display */}
      <div style={{
        marginTop: 20,
        padding: 16,
        background: GV.color.forestDeep,
        borderRadius: 12,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
      }}>
        <div>
          <div style={{
            fontFamily: GV.font.sans,
            fontSize: 10,
            fontWeight: 700,
            letterSpacing: '0.16em',
            color: GV.color.primaryFixedDim,
          }}>PREDICTED GV SCORE</div>
          <div style={{
            fontFamily: GV.font.sans,
            fontSize: 12,
            color: GV.color.white,
            marginTop: 4,
          }}>당신이 매기는 종합 평점</div>
        </div>
        <div style={{
          fontFamily: GV.font.serif,
          fontSize: 40,
          fontWeight: 700,
          color: GV.color.prestigeGold,
          letterSpacing: '-0.02em',
          lineHeight: 1,
        }}>{avg.toFixed(1)}</div>
      </div>

      <div style={{ marginTop: 20, display: 'grid', gap: 20 }}>
        {GV_QUALITY_AXES.map(axis => (
          <div key={axis.key}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <Icon name={axis.icon} size={18} color={GV.color.forestDeep} />
                <div>
                  <div style={{
                    fontFamily: GV.font.sans,
                    fontSize: 14,
                    fontWeight: 600,
                    color: GV.color.forestDeep,
                  }}>{axis.label}</div>
                  <div style={{
                    fontFamily: GV.font.sans,
                    fontSize: 10.5,
                    color: GV.color.outline,
                  }}>{axis.desc}</div>
                </div>
              </div>
              <div style={{
                fontFamily: GV.font.serif,
                fontSize: 22,
                fontWeight: 700,
                color: GV.color.forestDeep,
                minWidth: 40,
                textAlign: 'right',
              }}>{ratings[axis.key].toFixed(1)}</div>
            </div>
            <input
              type="range"
              min={1} max={10} step={0.1}
              value={ratings[axis.key]}
              onChange={e => set(axis.key, parseFloat(e.target.value))}
              style={{
                width: '100%',
                accentColor: GV.color.forestDeep,
              }}
            />
            <div style={{
              display: 'flex',
              justifyContent: 'space-between',
              fontFamily: GV.font.sans,
              fontSize: 10,
              color: GV.color.outline,
              marginTop: 2,
            }}>
              <span>1</span>
              <span>10</span>
            </div>
          </div>
        ))}
      </div>

      <button
        onClick={onNext}
        style={{
          marginTop: 32,
          width: '100%',
          background: GV.color.forestDeep,
          color: GV.color.white,
          border: 'none',
          borderRadius: 999,
          padding: '14px',
          fontFamily: GV.font.sans,
          fontSize: 15,
          fontWeight: 600,
          cursor: 'pointer',
        }}
      >다음 단계</button>
    </div>
  );
}

function ReviewStepPhotos({ photos, setPhotos, course, onNext }) {
  // Sample field photos to demo drag-drop feel
  const samples = ['assets/img_11.jpg', 'assets/img_15.jpg', 'assets/img_23.jpg', 'assets/img_20.jpg'];

  const addSample = (s) => {
    if (!photos.includes(s) && photos.length < 4) setPhotos([...photos, s]);
  };
  const removePhoto = (s) => setPhotos(photos.filter(p => p !== s));

  return (
    <div style={{ padding: '24px 20px 40px' }}>
      <h2 style={{
        fontFamily: GV.font.serif,
        fontSize: 22,
        fontWeight: 600,
        color: GV.color.forestDeep,
        margin: 0,
        letterSpacing: '-0.015em',
      }}>현장 사진을 추가해주세요</h2>
      <p style={{
        fontFamily: GV.font.sans,
        fontSize: 13,
        color: GV.color.onSurfaceVariant,
        margin: '6px 0 0',
        lineHeight: 1.5,
      }}>그린 상태, 코스 컨디션, 그늘집 사진은 다른 골퍼들에게 큰 도움이 됩니다.</p>

      {/* Selected photos */}
      <div style={{
        marginTop: 24,
        display: 'grid',
        gridTemplateColumns: '1fr 1fr',
        gap: 8,
      }}>
        {photos.map(p => (
          <div key={p} style={{
            position: 'relative',
            aspectRatio: '1',
            borderRadius: 10,
            backgroundImage: `url(${p})`,
            backgroundSize: 'cover',
            backgroundPosition: 'center',
          }}>
            <button
              onClick={() => removePhoto(p)}
              style={{
                position: 'absolute', top: 6, right: 6,
                width: 24, height: 24, borderRadius: 999,
                background: 'rgba(0,0,0,0.6)', color: 'white', border: 'none', cursor: 'pointer',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}
            >
              <Icon name="close" size={14} />
            </button>
          </div>
        ))}
        {photos.length < 4 && (
          <button style={{
            aspectRatio: '1',
            borderRadius: 10,
            background: GV.color.surfaceContainerLow,
            border: `1.5px dashed ${GV.color.outline}`,
            cursor: 'pointer',
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            justifyContent: 'center',
            gap: 4,
            color: GV.color.outline,
          }}>
            <Icon name="add_a_photo" size={28} />
            <span style={{ fontFamily: GV.font.sans, fontSize: 11, fontWeight: 500 }}>사진 추가</span>
          </button>
        )}
      </div>

      {/* Sample chips */}
      <div style={{ marginTop: 24 }}>
        <div style={{
          fontFamily: GV.font.sans,
          fontSize: 11,
          fontWeight: 700,
          letterSpacing: '0.14em',
          color: GV.color.outline,
          marginBottom: 10,
        }}>DEMO · 샘플 사진 눌러 추가</div>
        <div style={{ display: 'flex', gap: 8, overflowX: 'auto' }} className="gv-hscroll">
          {samples.map(s => (
            <button
              key={s}
              onClick={() => addSample(s)}
              disabled={photos.includes(s)}
              style={{
                width: 68, height: 68, flexShrink: 0,
                borderRadius: 8,
                border: 'none',
                backgroundImage: `url(${s})`,
                backgroundSize: 'cover',
                backgroundPosition: 'center',
                cursor: photos.includes(s) ? 'default' : 'pointer',
                opacity: photos.includes(s) ? 0.4 : 1,
                position: 'relative',
              }}
            >
              {!photos.includes(s) && (
                <div style={{
                  position: 'absolute', inset: 0,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  background: 'rgba(0,0,0,0.35)',
                  borderRadius: 8,
                  color: 'white',
                }}>
                  <Icon name="add" size={22} />
                </div>
              )}
            </button>
          ))}
        </div>
      </div>

      <div style={{
        marginTop: 20,
        padding: '10px 12px',
        background: GV.color.surfaceContainerLow,
        borderRadius: 8,
        display: 'flex',
        gap: 8,
        alignItems: 'flex-start',
      }}>
        <Icon name="info" size={16} color={GV.color.outline} />
        <span style={{
          fontFamily: GV.font.sans,
          fontSize: 11.5,
          color: GV.color.outline,
          lineHeight: 1.45,
        }}>다른 골퍼의 얼굴이나 캐디의 신상이 노출되지 않도록 주의해주세요.</span>
      </div>

      <button
        onClick={onNext}
        style={{
          marginTop: 32,
          width: '100%',
          background: GV.color.forestDeep,
          color: GV.color.white,
          border: 'none',
          borderRadius: 999,
          padding: '14px',
          fontFamily: GV.font.sans,
          fontSize: 15,
          fontWeight: 600,
          cursor: 'pointer',
        }}
      >{photos.length === 0 ? '건너뛰기' : '다음 단계'}</button>
    </div>
  );
}

function ReviewStepText({ text, setText, tags, setTags, onNext }) {
  const tagOptions = [
    '그린 상태 최상', '그린 빠름', '그린 느림',
    '진행 안정', '진행 지연',
    '캐디 프로페셔널', '캐디 친절', '캐디 아쉬움',
    '그늘집 만족', '그늘집 가격',
    '시설 프리미엄', '시설 노후',
    '가성비 우수', '가성비 아쉬움',
  ];
  const toggle = (t) => {
    setTags(tags.includes(t) ? tags.filter(x => x !== t) : [...tags, t]);
  };
  return (
    <div style={{ padding: '24px 20px 40px' }}>
      <h2 style={{
        fontFamily: GV.font.serif,
        fontSize: 22,
        fontWeight: 600,
        color: GV.color.forestDeep,
        margin: 0,
        letterSpacing: '-0.015em',
      }}>오늘의 라운드는 어떠셨나요?</h2>
      <p style={{
        fontFamily: GV.font.sans,
        fontSize: 13,
        color: GV.color.onSurfaceVariant,
        margin: '6px 0 0',
        lineHeight: 1.5,
      }}>구체적인 경험을 나눠주시면 다른 골퍼에게 큰 도움이 됩니다.</p>

      <textarea
        value={text}
        onChange={e => setText(e.target.value)}
        placeholder="예) 그린 스피드가 매우 빠르고 컨디션이 좋았습니다. 진행도 4시간 15분으로 쾌적했고..."
        rows={6}
        style={{
          marginTop: 20,
          width: '100%',
          padding: 14,
          border: `1px solid ${GV.color.borderSubtle}`,
          borderRadius: 12,
          fontFamily: GV.font.sans,
          fontSize: 14,
          color: GV.color.onSurface,
          resize: 'vertical',
          outline: 'none',
          background: GV.color.white,
          boxSizing: 'border-box',
          lineHeight: 1.55,
        }}
      />

      <div style={{ marginTop: 24 }}>
        <div style={{
          fontFamily: GV.font.serif,
          fontSize: 15,
          fontWeight: 600,
          color: GV.color.forestDeep,
        }}>경험 태그</div>
        <div style={{
          fontFamily: GV.font.sans,
          fontSize: 12,
          color: GV.color.outline,
          marginTop: 3,
        }}>해당되는 항목을 모두 선택해주세요 · {tags.length}개 선택</div>

        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 12 }}>
          {tagOptions.map(t => (
            <Chip key={t} active={tags.includes(t)} onClick={() => toggle(t)}>{t}</Chip>
          ))}
        </div>
      </div>

      <button
        onClick={onNext}
        style={{
          marginTop: 32,
          width: '100%',
          background: GV.color.forestDeep,
          color: GV.color.white,
          border: 'none',
          borderRadius: 999,
          padding: '14px',
          fontFamily: GV.font.sans,
          fontSize: 15,
          fontWeight: 600,
          cursor: 'pointer',
        }}
      >리뷰 게시하기</button>
    </div>
  );
}

function ReviewStepComplete({ course, nav, ratings, tagCount }) {
  const avg = Object.values(ratings).reduce((a, b) => a + b, 0) / Object.values(ratings).length;
  return (
    <div style={{ padding: '40px 20px', textAlign: 'center' }}>
      <div style={{
        width: 96, height: 96,
        borderRadius: 999,
        background: `linear-gradient(135deg, ${GV.color.prestigeGold} 0%, #b58a3f 100%)`,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        margin: '0 auto 20px',
        boxShadow: '0 10px 30px rgba(197,160,89,0.35)',
      }}>
        <Icon name="workspace_premium" size={52} color={GV.color.white} />
      </div>

      <h2 style={{
        fontFamily: GV.font.serif,
        fontSize: 22,
        fontWeight: 600,
        color: GV.color.forestDeep,
        margin: 0,
        letterSpacing: '-0.015em',
      }}>리뷰가 게시되었습니다</h2>
      <p style={{
        fontFamily: GV.font.sans,
        fontSize: 13,
        color: GV.color.onSurfaceVariant,
        margin: '8px 0 0',
        lineHeight: 1.55,
      }}>당신의 리뷰가 <b style={{ color: GV.color.forestDeep }}>{course.name}</b>의<br/>Green Voice 점수에 반영됩니다.</p>

      <Card style={{ marginTop: 24, textAlign: 'left' }}>
        <div style={{ padding: 16 }}>
          <div style={{
            fontFamily: GV.font.sans,
            fontSize: 10,
            fontWeight: 700,
            letterSpacing: '0.16em',
            color: GV.color.secondary,
          }}>YOUR CONTRIBUTION</div>
          <div style={{
            marginTop: 12,
            display: 'grid',
            gridTemplateColumns: '1fr 1fr 1fr',
            gap: 8,
            textAlign: 'center',
          }}>
            <div>
              <div style={{ fontFamily: GV.font.serif, fontSize: 20, fontWeight: 700, color: GV.color.forestDeep }}>{avg.toFixed(1)}</div>
              <div style={{ fontFamily: GV.font.sans, fontSize: 10, color: GV.color.outline, marginTop: 2 }}>내 평균 점수</div>
            </div>
            <div>
              <div style={{ fontFamily: GV.font.serif, fontSize: 20, fontWeight: 700, color: GV.color.forestDeep }}>{tagCount}</div>
              <div style={{ fontFamily: GV.font.sans, fontSize: 10, color: GV.color.outline, marginTop: 2 }}>태그 선택</div>
            </div>
            <div>
              <div style={{ fontFamily: GV.font.serif, fontSize: 20, fontWeight: 700, color: GV.color.prestigeGold }}>+3</div>
              <div style={{ fontFamily: GV.font.sans, fontSize: 10, color: GV.color.outline, marginTop: 2 }}>신뢰 지수</div>
            </div>
          </div>
        </div>
      </Card>

      <div style={{ marginTop: 24, display: 'grid', gap: 10 }}>
        <button
          onClick={nav.back}
          style={{
            background: GV.color.forestDeep,
            color: GV.color.white,
            border: 'none',
            borderRadius: 999,
            padding: '14px',
            fontFamily: GV.font.sans,
            fontSize: 15,
            fontWeight: 600,
            cursor: 'pointer',
          }}
        >완료</button>
      </div>
    </div>
  );
}

Object.assign(window, { GVReviewFlow });
