// Sentiment Analyst - Main Application
const { useState, useEffect, useMemo } = React;
const {
    Layout,
    Row,
    Col,
    Card,
    Button,
    Input,
    Select,
    Slider,
    Table,
    Tag,
    Statistic,
    Space,
    Typography,
    Popconfirm,
    message,
    Progress,
    Empty,
    Tooltip,
    ConfigProvider
} = antd;

const {
    GlobalOutlined,
    TwitterOutlined,
    FileTextOutlined,
    DeleteOutlined,
    SaveOutlined,
    SmileOutlined,
    MehOutlined,
    FrownOutlined,
    BarChartOutlined,
    LinkOutlined,
    GoogleOutlined,
    DesktopOutlined,
    TeamOutlined,
    QuestionCircleOutlined
} = icons;

const { Header, Content } = Layout;
const { Title, Text, Paragraph } = Typography;

// Initialize dayjs locale
dayjs.locale('ja');

// Constants
const STORAGE_KEY = 'sentiment_records';

const SOURCE_OPTIONS = [
    { value: 'Yahoo', label: 'Yahoo!ニュース', color: 'red' },
    { value: 'Google', label: 'Google News', color: 'blue' },
    { value: 'SNS', label: 'SNS', color: 'cyan' },
    { value: 'TV', label: 'TV', color: 'purple' },
    { value: 'Work', label: '仕事関連', color: 'orange' },
    { value: 'Other', label: 'その他', color: 'default' }
];

const NEWS_LINKS = [
    { name: 'Yahoo!ニュース', url: 'https://news.yahoo.co.jp/topics', icon: <GlobalOutlined /> },
    { name: 'Google News', url: 'https://news.google.com/topstories?hl=ja&gl=JP&ceid=JP:ja', icon: <GoogleOutlined /> },
    { name: '日本経済新聞', url: 'https://www.nikkei.com/', icon: <FileTextOutlined /> },
    { name: 'NHK NEWS', url: 'https://www3.nhk.or.jp/news/', icon: <DesktopOutlined /> }
];

// Utility functions
const generateId = () => {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
        const r = Math.random() * 16 | 0;
        const v = c === 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
};

const getScoreColor = (score) => {
    if (score > 10) return '#52c41a';
    if (score < -10) return '#ff4d4f';
    return '#faad14';
};

const getScoreClass = (score) => {
    if (score > 10) return 'score-positive';
    if (score < -10) return 'score-negative';
    return 'score-neutral';
};

const getSliderClass = (score) => {
    if (score > 10) return 'positive-slider';
    if (score < -10) return 'negative-slider';
    return 'neutral-slider';
};

const getScoreIcon = (score) => {
    if (score > 10) return <SmileOutlined style={{ color: '#52c41a' }} />;
    if (score < -10) return <FrownOutlined style={{ color: '#ff4d4f' }} />;
    return <MehOutlined style={{ color: '#faad14' }} />;
};

// Main App Component
const App = () => {
    const [records, setRecords] = useState([]);
    const [headline, setHeadline] = useState('');
    const [source, setSource] = useState('Yahoo');
    const [score, setScore] = useState(0);
    const [messageApi, contextHolder] = message.useMessage();

    // Load records from localStorage on mount
    useEffect(() => {
        try {
            const stored = localStorage.getItem(STORAGE_KEY);
            if (stored) {
                const parsed = JSON.parse(stored);
                setRecords(parsed);
            }
        } catch (error) {
            console.error('Failed to load records:', error);
        }
    }, []);

    // Save records to localStorage whenever they change
    useEffect(() => {
        try {
            localStorage.setItem(STORAGE_KEY, JSON.stringify(records));
        } catch (error) {
            console.error('Failed to save records:', error);
        }
    }, [records]);

    // Calculate average score
    const averageScore = useMemo(() => {
        if (records.length === 0) return 0;
        const sum = records.reduce((acc, r) => acc + r.score, 0);
        return Math.round(sum / records.length);
    }, [records]);

    // Handle form submission
    const handleSubmit = () => {
        if (!headline.trim()) {
            messageApi.warning('見出しを入力してください');
            return;
        }

        const newRecord = {
            id: generateId(),
            timestamp: new Date().toISOString(),
            headline: headline.trim(),
            source,
            score
        };

        setRecords(prev => [newRecord, ...prev]);
        setHeadline('');
        setScore(0);
        messageApi.success('記録を保存しました');
    };

    // Handle record deletion
    const handleDelete = (id) => {
        setRecords(prev => prev.filter(r => r.id !== id));
        messageApi.success('記録を削除しました');
    };

    // Table columns configuration
    const columns = [
        {
            title: '日付',
            dataIndex: 'timestamp',
            key: 'timestamp',
            width: 140,
            render: (timestamp) => (
                <div style={{ whiteSpace: 'nowrap' }}>
                    <Text style={{ fontSize: 14, fontWeight: 500 }}>
                        {dayjs(timestamp).format('MM/DD HH:mm')}
                    </Text>
                </div>
            ),
            sorter: (a, b) => new Date(b.timestamp) - new Date(a.timestamp),
            defaultSortOrder: 'descend'
        },
        {
            title: 'ソース',
            dataIndex: 'source',
            key: 'source',
            width: 110,
            render: (source) => {
                const opt = SOURCE_OPTIONS.find(o => o.value === source);
                return <Tag color={opt?.color || 'default'} style={{ fontSize: 13, padding: '2px 8px' }}>{source}</Tag>;
            },
            filters: SOURCE_OPTIONS.map(o => ({ text: o.label, value: o.value })),
            onFilter: (value, record) => record.source === value
        },
        {
            title: '見出し',
            dataIndex: 'headline',
            key: 'headline',
            ellipsis: {
                showTitle: false,
            },
            render: (text) => (
                <Tooltip title={text} placement="topLeft">
                    <Text style={{ fontSize: 14, lineHeight: '1.6' }}>{text}</Text>
                </Tooltip>
            )
        },
        {
            title: 'スコア',
            dataIndex: 'score',
            key: 'score',
            width: 140,
            align: 'center',
            render: (score) => (
                <Space direction="vertical" size={4} style={{ width: '100%' }}>
                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8 }}>
                        {getScoreIcon(score)}
                        <Text strong className={getScoreClass(score)} style={{ fontSize: 16, minWidth: 40, textAlign: 'center' }}>
                            {score > 0 ? `+${score}` : score}
                        </Text>
                    </div>
                    <Progress
                        percent={((score + 50) / 100) * 100}
                        size="small"
                        showInfo={false}
                        strokeColor={getScoreColor(score)}
                        trailColor="#f0f0f0"
                        style={{ margin: 0 }}
                    />
                </Space>
            ),
            sorter: (a, b) => a.score - b.score
        },
        {
            title: '',
            key: 'action',
            width: 70,
            align: 'center',
            render: (_, record) => (
                <Popconfirm
                    title="この記録を削除しますか？"
                    onConfirm={() => handleDelete(record.id)}
                    okText="削除"
                    cancelText="キャンセル"
                    okButtonProps={{ danger: true }}
                >
                    <Button
                        type="text"
                        danger
                        icon={<DeleteOutlined />}
                        size="middle"
                    />
                </Popconfirm>
            )
        }
    ];

    // Slider marks
    const sliderMarks = {
        '-50': { style: { color: '#ff4d4f' }, label: 'Bad' },
        '0': { style: { color: '#faad14' }, label: 'Neutral' },
        '50': { style: { color: '#52c41a' }, label: 'Good' }
    };

    return (
        <ConfigProvider
            theme={{
                token: {
                    colorPrimary: '#1890ff',
                    borderRadius: 8,
                }
            }}
        >
            {contextHolder}
            <Layout style={{ minHeight: '100vh' }}>
                {/* Header */}
                <Header className="app-header" style={{ height: 'auto' }}>
                    <Row gutter={[16, 16]} align="middle" justify="space-between">
                        <Col xs={24} sm={12}>
                            <Space align="center">
                                <BarChartOutlined style={{ fontSize: 28, color: '#fff' }} />
                                <Title level={3} style={{ margin: 0, color: '#fff' }}>
                                    Sentiment Analyst
                                </Title>
                            </Space>
                        </Col>
                        <Col xs={24} sm={12}>
                            <Card
                                size="small"
                                style={{ 
                                    background: 'rgba(255,255,255,0.95)',
                                    borderRadius: 8,
                                }}
                                bodyStyle={{ padding: '8px 16px' }}
                            >
                                <Row gutter={16} align="middle">
                                    <Col>
                                        {getScoreIcon(averageScore)}
                                    </Col>
                                    <Col>
                                        <Statistic
                                            title="平均感情スコア"
                                            value={averageScore}
                                            prefix={averageScore > 0 ? '+' : ''}
                                            valueStyle={{ 
                                                color: getScoreColor(averageScore),
                                                fontSize: 24,
                                                fontWeight: 'bold'
                                            }}
                                        />
                                    </Col>
                                    <Col>
                                        <Text type="secondary" style={{ fontSize: 12 }}>
                                            ({records.length} 件の記録)
                                        </Text>
                                    </Col>
                                </Row>
                            </Card>
                        </Col>
                    </Row>
                </Header>

                {/* Main Content */}
                <Content style={{ padding: '24px', maxWidth: 1400, margin: '0 auto', width: '100%' }}>
                    <Row gutter={[24, 24]}>
                        {/* Left Column - News Dock */}
                        <Col xs={24} md={8} lg={6}>
                            <Card
                                title={
                                    <Space>
                                        <LinkOutlined />
                                        <span>News Dock</span>
                                    </Space>
                                }
                                style={{ height: '100%' }}
                            >
                                <Paragraph type="secondary" style={{ marginBottom: 16 }}>
                                    下のリンクからニュースサイトにアクセスし、気になる見出しをコピーして戻ってください。
                                </Paragraph>
                                <Space direction="vertical" style={{ width: '100%' }}>
                                    {NEWS_LINKS.map((link) => (
                                        <Button
                                            key={link.name}
                                            className="news-btn"
                                            icon={link.icon}
                                            href={link.url}
                                            target="_blank"
                                            rel="noopener noreferrer"
                                        >
                                            {link.name}
                                        </Button>
                                    ))}
                                </Space>
                            </Card>
                        </Col>

                        {/* Right Column - Analyze Console */}
                        <Col xs={24} md={16} lg={18}>
                            <Card
                                title={
                                    <Space>
                                        <FileTextOutlined />
                                        <span>Analyze Console</span>
                                    </Space>
                                }
                            >
                                <Space direction="vertical" size="large" style={{ width: '100%' }}>
                                    {/* Headline Input */}
                                    <div>
                                        <Text strong style={{ display: 'block', marginBottom: 8 }}>
                                            ニュース見出し
                                        </Text>
                                        <Input.TextArea
                                            value={headline}
                                            onChange={(e) => setHeadline(e.target.value)}
                                            placeholder="見出しをここにペースト..."
                                            autoSize={{ minRows: 2, maxRows: 4 }}
                                            maxLength={500}
                                            showCount
                                        />
                                    </div>

                                    <Row gutter={[24, 16]}>
                                        {/* Source Select */}
                                        <Col xs={24} sm={8}>
                                            <Text strong style={{ display: 'block', marginBottom: 8 }}>
                                                ソース
                                            </Text>
                                            <Select
                                                value={source}
                                                onChange={setSource}
                                                style={{ width: '100%' }}
                                                options={SOURCE_OPTIONS.map(o => ({
                                                    value: o.value,
                                                    label: (
                                                        <Space>
                                                            <Tag color={o.color} style={{ marginRight: 0 }}>
                                                                {o.value}
                                                            </Tag>
                                                            <span>{o.label}</span>
                                                        </Space>
                                                    )
                                                }))}
                                            />
                                        </Col>

                                        {/* Score Slider */}
                                        <Col xs={24} sm={16}>
                                            <Text strong style={{ display: 'block', marginBottom: 8 }}>
                                                感情スコア: {' '}
                                                <Text 
                                                    strong 
                                                    className={getScoreClass(score)}
                                                    style={{ fontSize: 18 }}
                                                >
                                                    {score > 0 ? `+${score}` : score}
                                                </Text>
                                            </Text>
                                            <div className={getSliderClass(score)}>
                                                <Slider
                                                    value={score}
                                                    onChange={setScore}
                                                    min={-50}
                                                    max={50}
                                                    marks={sliderMarks}
                                                    tooltip={{
                                                        formatter: (val) => val > 0 ? `+${val}` : val
                                                    }}
                                                />
                                            </div>
                                        </Col>
                                    </Row>

                                    {/* Submit Button */}
                                    <Button
                                        type="primary"
                                        icon={<SaveOutlined />}
                                        onClick={handleSubmit}
                                        size="large"
                                        block
                                    >
                                        記録する
                                    </Button>
                                </Space>
                            </Card>
                        </Col>
                    </Row>

                    {/* Records Table */}
                    <Card
                        title={
                            <Space>
                                <BarChartOutlined />
                                <span>記録一覧</span>
                                <Tag>{records.length} 件</Tag>
                            </Space>
                        }
                        style={{ marginTop: 24 }}
                    >
                        {records.length === 0 ? (
                            <Empty
                                image={Empty.PRESENTED_IMAGE_SIMPLE}
                                description="まだ記録がありません"
                            >
                                <Text type="secondary">
                                    上のフォームからニュースの感情分析を記録してみましょう
                                </Text>
                            </Empty>
                        ) : (
                            <Table
                                dataSource={records}
                                columns={columns}
                                rowKey="id"
                                pagination={{
                                    pageSize: 10,
                                    showSizeChanger: true,
                                    showTotal: (total) => `全 ${total} 件`,
                                    pageSizeOptions: ['5', '10', '20', '50']
                                }}
                                scroll={{ x: 600 }}
                                size="middle"
                                rowClassName={() => 'table-row'}
                                style={{ fontSize: 14 }}
                            />
                        )}
                    </Card>
                </Content>
            </Layout>
        </ConfigProvider>
    );
};

// Render the app
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
